To find a value in an unsorted array you have to look at every element. In a sorted array, one comparison tells you much more: if the target is smaller than the value you looked at, it can only be to its left. Look at the middle value, and each comparison rules out half of what's left.
Keep two indices, lo and hi: the range that could still hold the target. They start at the two ends of the array. While lo ≤ hi:
If lo passes hi, the range is empty and the target isn't there. At that moment lo is the index where the target would have to be inserted to keep the array sorted, which is often just as useful.
in range could still be the target mid the value being compared out ruled out found the target
Binary search is short, but it's famously easy to get subtly wrong:
| Binary search | Linear search | |
|---|---|---|
| Comparisons | At most ⌊log₂ n⌋ + 1: 4 for the 11 values above, 20 for a million | Up to n |
| Needs | Sorted data with fast access by index | Nothing |
A binary search tree stores the same idea as a structure: each node is a "mid", and each comparison picks a side.