Binary Search: The Optimal Number-Guessing Game
That easy green line O(log n) from last lesson—today we unmask it. Did you play “I'm thinking of a number from 1 to 100, you guess” as a kid? The optimal strategy for guessing numbers is one of the classic algorithms in computer science—binary search. Play first, then talk theory.
The system has already picked a number from 1 to 100. The strip below is every candidate: tap any number to guess—I'll tell you too high or too low, and eliminated numbers gray out. First guess randomly by instinct and note the count, then hit “Guess by binary search” for the textbook answer. Watch: each binary guess cuts the lit region exactly in half.
The power of “cut in half” really shows when data gets big. Tap a data size below, see how many binary guesses you need at most, then watch the “fold in half” animation. Watch: data ×10,000, and the try count only climbs from 7 to a bit over 20.
⚠️ Important premise: binary search's ticket in is “sort first”
The guessing game works because numbers have a natural order—“too high” only means something then. Swap in a dictionary with shuffled page numbers, flip to the middle and see “cat,” and you have no idea whether “dog” is left or right—binary search dies on the spot. So to enjoy O(log n) search, you pay the sorting cost first—how sorting works and how expensive it is is exactly next lesson's star.
Flip a dictionary / phone book
Looking up “Wang” you don't start at page one: flip to the middle, compare the spelling, toss half—the motion in your hands is binary search.
git bisect finds the bad commit
One of 1000 commits introduced a bug? git jumps to the middle commit for you to test, keep the bad half / drop the good half, lock the culprit within 10 tries.
Guess the price / tune a parameter
“How much is this bottle?”“Too high.”“Too low.”—TV price-guess segments: the pros are doing binary search in their heads. Manual hyperparameter search is the same move.
What this lesson wants to share
- Power of cutting in half: 100 candidates → 7 tries; a billion candidates still only 30—that's O(log n)
- Not luck—a guarantee: binary search gives a worst-case upper bound; engineering wants determinism
- Order is the premise: a shuffled dictionary can't be flipped; to use binary search, pay for sorting first (next lesson)
- Everyday form: dictionaries, git bisect for bad commits, price guessing—all binary search