All episodes · From a List to Your Map App · Episode 5

Binary Search: Find Anything in 20 Guesses

Pressing play loads the video from YouTube.

Think of a number from 1 to 100: seven guesses are always enough. The same trick finds one name among a million in twenty steps, and among a billion in thirty.
We see why seven is enough (2⁷ = 128), write binary search with two markers, low and high, show why the list must be sorted first, catch the one-character bug almost every programmer writes once, and use it to find which of a thousand versions first broke, in ten tests.

Every animation in this video is drawn by code, and the narration is an AI voice.

Transcript

Think of a number from one to a hundred. I'll find it in seven guesses or fewer, every time. Fifty? Higher. Seventy-five? Lower. Sixty-two? Higher. Sixty-eight? Lower. Sixty-five, sixty-six: higher. Sixty-seven. That's binary search. Today: how it works, why it needs a sorted list, and the one bug almost everyone writes.

Every guess cuts the range in half: a hundred, fifty, twenty-five, twelve, six, three, one. Each doubling of the range adds just one guess. Two to the seventh is a hundred and twenty-eight, so seven is always enough. A million needs twenty guesses, a billion needs thirty. That count of halvings is log base two of n.

In a program, two markers hold the range that's still possible: low and high. Look at the middle. If it's too small, move low just past it. If it's too big, move high just below it. Stop when you find it, or when low passes high. Then the number isn't there at all.

All of this only works because the list is sorted. Shuffle it, and “too small” no longer tells you which half to throw away. So if you'll search many times, sorting first pays off. That's what the next four episodes are about.

Now the bug. Write “move low to the middle” instead of “just past the middle”, and watch what happens. With two numbers left, the middle is low itself. Low never moves, and the loop runs forever. One “plus one” decides whether it ever finishes. Always test the tiny cases: one item, and two items.

Binary search is everywhere: looking up a word in a sorted dictionary, or finding exactly where a new item should go. It can even find which of a thousand versions of a program first broke. Test the middle one, keep the half that changed: about ten tests in all.

Binary search: keep the half that can still hold the answer, until just one is left. Next time: how does a list get sorted in the first place? Three simple ways you could do by hand. See you there.

Next episode: sorting by hand, with insertion, selection and bubble sort.

Buy the Developer a Coffee

Entirely up to you: it works the same either way.

Every cup turns into the next update.

WeChat Pay QR code
WeChat Pay
Alipay QR code
Alipay
PayPal QR code
PayPal