In writing some code today, I have happened upon a circumstance that has caused me to write a binary search of a kind I have never seen before. Does this binary search have a name, and is it really a "binary" search?
Motivation
First of all, in order to make the search easier to understand, I will explain the use case that spawned its creation.
Say you have a list of ordered numbers. You are asked to find the index of the number in the list that is closest to x.
int findIndexClosestTo(int x);
The calls to findIndexClosestTo()
always follow this rule:
If the last result of
findIndexClosestTo()
wasi
, then indices closer toi
have greater probability of being the result of the current call tofindIndexClosestTo()
.
In other words, the index we need to find this time is more likely to be closer to the last one we found than further from it.
For an example, imagine a simulated boy that walks left and right on the screen. If we are often querying the index of the boy's location, it is likely he is somewhere near the last place we found him.
Algorithm
Given the case above, we know the last result of findIndexClosestTo()
was i
(if this is actually the first time the function has been called, i
defaults to the middle index of the list, for simplicity, although a separate binary search to find the result of the first call would actually be faster), and the function has been called again. Given the new number x
, we follow this algorithm to find its index:
interval = 1;
- Is the number we're looking for,
x
, positioned ati
? If so, returni
; - If not, determine whether
x
is above or belowi
. (Remember, the list is sorted.) - Move
interval
indices in the direction ofx
. - If we have found
x
at our new location, return that location. - Double
interval
. (i.e.interval *= 2
) - If we have passed
x
, go backinterval
indices, setinterval = 1
, go to 4.
Given the probability rule stated above (under the Motivation header), this appears to me to be the most efficient way to find the correct index. Do you know of a faster way?