function binarySearch(array: number[], target: number) {let low = 0, high = array.length - 1;
while (low <= high) {const middle = (low + high) >> 1;
if (array[middle] === target) return middle;
if (array[middle] < target) low = middle + 1;
else high = middle - 1;
}
return -1;
}
Look for 33. The whole range [0, 31] is possible.
Understanding Binary search
The idea
Binary search keeps a range [low, high] that must contain the target, looks at the middle element, and throws away the half that cannot contain it. Because the array is sorted, one comparison tells which half: smaller means look left, larger means look right.
Each probe halves the range, so a million elements take at most twenty probes. The precondition is the whole trick: sorting once costs n log n, and after that every lookup is logarithmic.
The four stages
Complexity
Versus its siblings
Pseudocode
BINARYSEARCH(array, target)
low ← 0; high ← n − 1
while low ≤ high
middle ← ⌊(low + high) / 2⌋
if array[middle] = target: return middle
if array[middle] < target: low ← middle + 1 else high ← middle − 1
return −1
When to use
Pitfalls
History
John Mauchly presented binary search in 1946, in the same Moore School lectures that described insertion sort. The first version that worked for every array size was not published until 1962, by Lehmer and then Bottenbruch, and Jon Bentley found in 1986 that 90% of professional programmers could not write it correctly.