Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

1 · Why halving beats looking everywhere

In one sentence: in a sorted list, one look at the middle tells you which half the value can’t be in, so each look throws away half of what’s left, and a million items take 20 looks instead of a million.

The problem it solves

You have a list of a million order numbers and someone asks: is 1000000 in it? The obvious way is a scan: read the list from the start and compare each number. If the number is there, you stop when you reach it. If it isn’t there, you can only say so after reading every number.

On the Raspberry Pi 4 this course was written on, -1 in a on a list of a million numbers took 30.5 ms (best of 7 runs). That sounds small until it runs for every request, or inside a loop over another million items.

The idea: the guessing game

You’ve probably played this: “I’m thinking of a number from 0 to 99.” A good player never guesses 0, 1, 2, …; they guess 50. “Too high” throws away 50 to 99 in one go. Then 25, then whatever is in the middle of what’s left.

That works because the answers “too high” and “too low” tell you which side the number is on. A sorted list gives you the same answers for free: if the middle element is bigger than what you want, so is everything after it. That method is binary search (“binary” because each look splits what’s left in two).

Here are the real rounds for finding 37 in the sorted numbers 0 to 99 (the animation above shows the same run):

round 1: lo=0 hi=100 mid=50 a[mid]=50 > 37: keep left half, hi=50
round 2: lo=0 hi=50 mid=25 a[mid]=25 < 37: keep right half, lo=26
round 3: lo=26 hi=50 mid=38 a[mid]=38 > 37: keep left half, hi=38
round 4: lo=26 hi=38 mid=32 a[mid]=32 < 37: keep right half, lo=33
round 5: lo=33 hi=38 mid=35 a[mid]=35 < 37: keep right half, lo=36
round 6: lo=36 hi=38 mid=37 a[mid]=37 == 37: found
result: index 37 after 6 rounds

lo and hi mark the part of the list still in play, and mid is its middle. Lesson 2 is about exactly those three names. For now, just count the lines: 6 looks, where a scan from the start needs 38 (0, 1, …, 37).

How many looks: count the halvings

Each look halves what’s left. So the question “how many looks for n items?” is about “how many times can you halve n before nothing is left?”. That count has a name: the logarithm base 2 of n, written log₂ n. It’s the power you raise 2 to in order to get n: 2¹⁰ = 1,024, so log₂ 1,024 = 10 (the first Go deeper below gives the exact count).

Measured on this machine, the most rounds the search needed (up to 100,000 items: for every value in the list and a missing one on each side; for the two biggest lists, five values):

n itemsscan, value missingbinary search, at most
10104
1,0001,00010
1,000,0001,000,00020
1,000,000,0001,000,000,00030

Multiply the list by 1,000 and binary search needs about 10 more looks. The time agrees: on the same million numbers, the missing value took 6.3 µs instead of 30.5 ms, about 4,800 times less.

The one condition: sorted

Binary search trusts the list. When the middle is too big, it throws away everything after it without looking, because in a sorted list those are bigger too. On a list that isn’t sorted, that is a lie, and the search quietly gives wrong answers. Run on [8, 3, 9, 1, 5, 7, 2] for each of its own elements, it found only three:

unsorted [8, 3, 9, 1, 5, 7, 2]
  element 8: index -1, found=False
  element 3: index -1, found=False
  element 9: index -1, found=False
  element 1: index 3, found=True
  element 5: index 4, found=True
  element 7: index 5, found=True
  element 2: index -1, found=False

Sorted first, the same search finds all seven. No error, no warning: sorted is your job, not the search’s.

When to use which

SituationUse
a list searched once, or not sorteda scan (sorting costs more than one scan)
a sorted list searched many timesbinary search

Try it on your computer

Lesson 2 turns the guessing game into exact code. Practical 0 · Your binary search, after lesson 2, has you write it, then count its looks on a million numbers yourself.

Go deeper: why the worst case is log₂ n + 1, not log₂ n

The table’s “at most” column is exactly floor(log₂ n) + 1 on every row the course measured: 4 for 10 items, 20 for a million. floor means “rounded down”: log₂ 1,000,000 is about 19.93, which rounds down to 19, plus 1 is 20.

Why the + 1: halving 1,000,000 nineteen times leaves a window of 1 element, and that last element still has to be looked at. A missing value larger than everything took one round fewer on every row (19 for a million), because the window can also run out before reaching a single element. “About log₂ n” is the honest summary; “at most log₂ n + 1, rounded down” is the exact one.

Go deeper: a list that doesn't fit in memory

The same halving works on anything you can read by position: a sorted file of fixed-size records (jump to record mid with seek), or Python’s range, which computes range(n)[i] without storing anything. That’s how the billion-item row above was measured: range(1_000_000_000) is sorted, has a length, and answers a[mid], so binary search ran on it in 30 rounds without a billion numbers in memory.

Common misunderstandings

  • “Binary search is for numbers.” It works on anything that can be compared with <: strings, dates, tuples. Python compares strings character by character, so a list sorted with sorted() works the same way.
  • “20 looks means 20 times faster.” It means 20 looks instead of a million. The gap grows with the list.

Check yourself

1. Your list grows from 1 million to 2 million items. How many more looks does binary search need, at most? One. Doubling the list adds one halving: the first look cuts 2 million back to 1 million, and from there it's the same search as before.
2. A colleague's binary search sometimes says "not found" for values that are definitely in the list. No error. What do you check first? That the list is sorted, in the same order the search assumes (smallest first). An unsorted list gives exactly this: some values found, others reported missing, and nothing crashes.
3. A sorted list of a billion numbers needs at most 30 rounds. Your colleague's version of the search needs 31 rounds on some values. Is it wrong? Not necessarily wrong, but it does more than it needs to: halving a billion leaves one element after 29 halvings, and looking at that one is the 30th round. A 31st round means some round didn't shrink the window as much as it could, which is worth reading the code for: lesson 2 shows the rules each round has to follow.

Next: 2 · The window and its promise.