Finding even numbers in an array

后端 未结 1 1288
失恋的感觉
失恋的感觉 2021-02-08 16:10

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 functio

相关标签:
1条回答
  • 2021-02-08 16:34

    You can do a binary search instead. Write a function that does the following:

    • Start with A = array and n = length(A).
    • While n>1
      • Set L = [A[0],A[1],...,A[k-1]] and R = [A[k],A[k+1],...,A[n-1]] where k = floor(n/2)
      • If isEven(product of elements of L), then set A=L and n = k,
      • Otherwise set A=R and n = n-k.
    • If isEven(A[0]), return A[0],
    • Otherwise, return -1.

    Run a for loop that will have at most e iterations. Each time run the algorithm above to find an even number, if the output is -1 stop, there are no more to find. Otherwise, print the output, remove it from the array, and iterate for at most e trials.

    The binary search algorithm takes log(n) calls to isEven, and you must run it at most e times, so there are a total of e log(n) calls to isEven.

    Therefore you want to take this approach whenever e log(n) < n, otherwise use the linear search, which takes n calls to isEven.

    0 讨论(0)
提交回复
热议问题