There is a sorted array of infinite numbers, write an algorithm to search the element in the array?
Since the array is sorted, the first thing clicks into mind is binary search, but the problem here is that we don’t know the size of the array.
As the array is infinite, that means we don’t have proper bounds to apply binary search. So in order to search the element, first we find bounds and then apply a binary search algorithm.
Let low be pointing to 1st element and high pointing to 2nd element of the array. Now compare key with high index element:
1. If it is greater than the high index element then copies high index in the low index and double the high index.
2. if it is smaller, then apply binary search on high and low indices found.
Element found at index 4
Let p be the position of element to be searched. Number of steps for finding high index ‘h’ is O(Log p). The value of ‘h’ must be less than 2*p. The number of elements between h/2 and h must be O(p). Therefore, time complexity of Binary Search step is also O(Log p) and overall time complexity is 2*O(Log p) which is O(Log p).