Programming Fundamentals · Search and Sorting

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.

Interactive 1 · Number-guessing game

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.

Tap any number on the strip to start guessing → 0 tries
Why at most 7 tries? 100 candidates → cut to 50, then 25, 12, 6, 3, 1… seven cuts leave exactly one. Random guessing can take dozens on a bad day, and even luck isn't stable; binary search doesn't rely on luck—it gives a worst-case guarantee—exactly what engineers care about most.
Interactive 2 · A billion items in only 30 tries

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.

At most 7 tries (ceil of log₂ n)
100 items
Pink bar = candidates not yet eliminated. Tap a data-size button above and watch it fold in half repeatedly.

⚠️ 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.

Everyday form · You've been using binary search all along
📖

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