The selected answer is not optimal. If you are trying to minimize the number of probes (array search), you can do better than searching from the very beginning, and the steps that reach the whole `target - array[i]
Since you are allowed to do random access using indexed searches, you can make much more progress. For example, if you are looking for 9 in an array that starts with a[0] = 0 , you can examine a[16] to see if it is less than or equal to 0. If not, then none of a[0 .. 16] may reach 9.
Big steps give you more information for each probe (each probe allows you to exclude signs both on the left and on the right). This allows you to get twice as much information for each probe when compared to the minimum steps when searching on the left.
To demonstrate the benefits of search-from-mid compared to search-from-left, here is some working code written in the Python programming language:
def find(arr, value, bias=2):
Conceptually, what the algorithm does is an attempt to obtain the maximum amount of information possible with each probe. Sometimes he is lucky and immediately exclude large ranges; sometimes it will be unsuccessful and will only be able to eliminate a tiny subrange. Regardless of luck, his exclusion zone will be twice as large as the search from the left.
Simple test code:
arr = [10, 11, 12, 13, 14, 13, 12, 11, 10, 9, 8, 7, 6, 7, 8] for i in range(min(arr), max(arr)+1): assert arr.index(i) == find(arr, i)