Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search in infinite array using binary search

Tags:

arrays

binary

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.

like image 213
niyon01 Avatar asked Oct 19 '25 12:10

niyon01


1 Answers

It will no longer qualify as a pure binary search, but here's one approach.

For an array array and a search value s:

  1. Decide on a block size n (e.g. n = 1000)
    Define an initial index i corresponding to the first element in the array (i = 1)
  2. Compare the search value s to the value at array[n]
  3. Then:
    1. If array[n] is greater than s:
      Continue with a regular binary search between array[i] and array[n]
    2. If array[n] is less than s:
      Move the index: i = i + n
      Double the block size: n = n * 2
      Start over at step 2.
like image 179
Robby Cornelissen Avatar answered Oct 21 '25 01:10

Robby Cornelissen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!