Given an infinite length sorted array having both positive and negative integers. Find an element in it.
EDIT
All the elements in the array are unique and the array in infinite in right direction.
There are two approaches:
Approach 1:
Set the index at position 100, if the element to be found is less, binary search in the previous 100 items, else set the next index at position 200. In this way, keep on increasing the index by 100 until the item is greater.
Approach 2:
Set the index in power of 2. First set the index at position 2, then 4, then 8, then 16 and so on. Again do the binary search from position 2^K to 2^(K + 1) where item is in between.
Which of the two approaches will be better both in best case and worst case?
The first approach will be linear in the index of the element (
O(k)wherekis the index of the element). Actually, you are going to needk/100iterations to find the element which is greater than the searched element, which isO(k).The second approach will be logarithmic in the same index.
O(logk). (wherekis the index of the element). In here, you are going to needlog(k)iterations until you find the higher element. Then binary search between2^(i-1),2^i(whereiis the iteration number), will be logarithmic as well, totaling inO(logk)Thus, the second is more efficient.