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.