How should I use binary search to find if there is a distance between neighbor numbers greater than N in a sorted array? For example:
Input: 2 5 8 11 16
Distance: 4
So we should get answer that there is such distance between neighbors. (between 11 and 16)
EDIT: Let me be more clear why I want to do this with binary search.
Assume that the INPUT array comes unsorted. Ex:
Input: 11 8 2 16 5
Then you should sort the array to see which are the neighbors. So after we have a sorted list isn’t it the best way to find the distance with some mutation of binary search?
You cannot use binary search in the worst case scenario, when all numbers are equally spaced at
N.The idea of a binary search and other divide-and-conquer algorithms is that you eliminate roughly half of the remaining range at each step. When all items are spaced at
N, every range of three or more consecutive items could potentially contain a pair of neighbors with the distance of> N, so you cannot eliminate either one of the two sub-ranges under consideration. You will eventually examine every single pair of consecutive items, costing youO(NumItems).That said, you can probably optimize a general case to do considerably better than
O(NumItems)because of potential pruning opportunities.