Given a bitonic array and element x in the array, find the index of x in 2log(n) time

后端 未结 7 1068
我寻月下人不归
我寻月下人不归 2021-01-29 22:14

First, a bitonic array for this question is defined as one such that for some index K in an array of length N where 0 < K < N - 1 an

7条回答
  •  -上瘾入骨i
    2021-01-29 22:33

    The algorithm works recursively by combining bitonic and binary searches:

    def bitonic_search (array, value, lo = 0, hi = array.length - 1)
      if array[lo] == value then return lo
      if array[hi] == value then return hi
      mid = (hi + lo) / 2
      if array[mid] == value then return mid
      if (mid > 0 & array[mid-1] < array[mid])
         | (mid < array.length-1 & array[mid+1] > array[mid]) then
        # max is to the right of mid
        bin = binary_search(array, value, low, mid-1)
        if bin != -1 then return bin
        return bitonic_search(array, value, mid+1, hi)
      else # max is to the left of mid
        bin = binary_search(array, value, mid+1, hi)
        if bin != -1 then return bin
        return bitonic_search(array, value, lo, mid-1)        
    

    So the recursive formula for the time is f(l) = f(l/2) + log(l/2) + c where log(l/2) comes from the binary search and c is the cost of the comparisons done in the function body.

提交回复
热议问题