Suppose, the array is infinite. So, the problem here is that we don’t know the size of the array. If the array is infinite, that means we don’t have proper bounds to apply binary search. So in order to find the position of the key, what can I do.
1 Answer
It will no longer qualify as a pure binary search, but here's one approach.
For an array array and a search value s:
- Decide on a block size
n(e.g.n = 1000)
Define an initial indexicorresponding to the first element in the array (i = 1) - Compare the search value
sto the value atarray[n] - Then:
- If
array[n]is greater thans:
Continue with a regular binary search betweenarray[i]andarray[n] - If
array[n]is less thans:
Move the index:i = i + n
Double the block size:n = n * 2
Start over at step 2.
- If