← chapter

Binary search

Look at the middle, discard the half that can't contain it. O(log n) on sorted data.

Each probe halves the candidates

Watch the window collapse

21 elements, target 30 → found in 5 probes. Blue window halves every step.

O(log n) vs O(n)

Linear scan climbs and drops off the chart. Binary/bisect stay flat.

Famous for being buggy

Takeaway

Search sorted data with a logarithm, never a scan. Generalizes to "binary search on the answer". Next: quickselect.