Given an array of length n containing at most e even numbers and a
function isEven that returns true if the input is even and false
otherwise, write a function that prints all the even numbers in the
array using the fewest number of calls to isEven.
The only thing I could think was to do a linear search and stop after I hit the end of the array or found e even numbers. Can someone please tell me a better way?
You can do a binary search instead. Write a function that does the following:
A = arrayandn = length(A).n>1L = [A[0],A[1],...,A[k-1]]andR = [A[k],A[k+1],...,A[n-1]]wherek = floor(n/2)isEven(product of elements of L), then setA=Landn = k,A=Randn = n-k.isEven(A[0]), returnA[0],-1.Run a
forloop that will have at mosteiterations. Each time run the algorithm above to find an even number, if the output is-1stop, there are no more to find. Otherwise, print the output, remove it from the array, and iterate for at mostetrials.The binary search algorithm takes
log(n)calls toisEven, and you must run it at mostetimes, so there are a total ofe log(n)calls toisEven.Therefore you want to take this approach whenever
e log(n) < n, otherwise use the linear search, which takesncalls toisEven.