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

后端 未结 7 1066
我寻月下人不归
我寻月下人不归 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条回答
  • 2021-01-29 22:53

    There are 5 main cases depending on where the max element of array is, and whether middle element is greater than desired value

    Calculate middle element. Compare middle element desired value, if it matches search ends. Otherwise proceed to next step.

    1. Compare middle element with neighbors to see if max element is on left or right. If both of the neighbors are less than middle element, then element is not present in the array, hence exit.(Array mentioned in the question will hit this case first as 14, the max element, is in middle)

    2. If middle element is less than desired value and max element is on right, do bitonic search in right subarray

    3. If middle element is less than desired value and max element is on left, do bitonic search in left subarray

    4. If middle element is greater than desired value and max element is on left, do descending binary search in right subarray

    5. If middle element is greater than desired value and max element is on right, do ascending binary search in left subarray

    In the worst case we will be doing two comparisons each time array is divided in half, hence complexity will be 2*logN

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