12/41
Part 2 of 7 · Binary searchLearn and do

Each look at least halves the range, so a million items take at most 20 looks

While lo < hi, the middle (lo + hi) // 2 is at least lo and less than hi. So lo = mid + 1 moves lo up by at least one, and hi = mid moves hi down by at least one. Each look cuts the unsettled range at least in half.

That's at most ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 looks: log base 2 of n, rounded down, plus one. Measured by running the loop to every boundary: 4 looks for 8 items, 10 for 1,000, 20 for a million, 30 for a billion.

On a million sorted integers, finding a target past the end:

One search for a target past the end, a million sorted integers, log scale
a scan from the left
22.31 ms
first_at_or_after
1.13 µs
bisect_left
143 ns

The loop by hand is about 20,000 times faster than the scan. bisect runs the same loop in C, for another factor of 8.

In the editor, write max_looks(n). It prints the most looks for 8 items, a thousand, a million and a billion.