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

2 · The window and its promise

In one sentence: keep a window [lo, hi) (lo is in it, hi is not) that always holds the value if the value is in the list at all; shrink it from the middle until you find the value or the window is empty.

The problem it solves

Lesson 1’s idea fits in one sentence: look in the middle, throw away half. Code needs more than that. It needs exact answers to three small questions, and almost every broken binary search gets one of them slightly wrong:

  1. How do you write down which part of the list is still in play?
  2. Which element is “the middle”?
  3. When do you stop?

A wrong answer doesn’t crash, most of the time. It skips one element, or never stops, on some lists only.

The idea: a window with one promise

The window. Two numbers mark the part still in play: lo, the first position in it, and hi, the first position after it. Mathematicians write that [lo, hi): the square bracket means “included”, the round one “not included”. It’s the same convention as Python’s range(lo, hi) and a[lo:hi], so the window holds hi - lo elements, and lo == hi means empty.

At the start the window is the whole list: lo = 0, hi = len(a). Position len(a) doesn’t exist, which is fine: hi is never looked at.

The promise. Everything the code does keeps one sentence true:

If x is in the list, it’s inside the window.

A sentence that the code keeps true before and after every round is called an invariant. It’s what you check each line against: a line is right if it can’t break the promise.

How it works

The middle. mid = (lo + hi) // 2. The // divides and rounds down. While the window isn’t empty, that always lands inside it, lo <= mid < hi, even for a window of one:

lo=0 hi=10 mid=5 lo <= mid < hi: True
lo=0 hi=1 mid=0 lo <= mid < hi: True
lo=5 hi=6 mid=5 lo <= mid < hi: True
lo=5 hi=7 mid=6 lo <= mid < hi: True
lo=3 hi=3: window empty, loop does not run

One comparison, one edge moves. The list is sorted, so a[mid] tells you which side x can’t be on:

a[mid] compared with xWhat it tells youMoveWhy the promise holds
a[mid] < xx is right of midlo = mid + 1mid and everything left of it are too small
a[mid] > xx is left of midhi = midmid and everything right of it are too big; hi isn’t in the window, so mid leaves
equalfoundreturn mid

The asymmetry is the whole trick. Both moves throw mid out of the window. On the left that takes + 1 (lo is included, so it must move past mid); on the right it doesn’t (hi is excluded, so hi = mid already leaves mid out).

When to stop. while lo < hi: while the window isn’t empty. When it empties, the promise says x was never in the list, so return -1.

What it looks like

def search(a, x):
    """Index of x in the sorted list a, or -1 if x isn't there."""
    lo, hi = 0, len(a)              # the window [lo, hi): lo is in it, hi is not
    while lo < hi:                  # the window isn't empty
        mid = (lo + hi) // 2        # lo <= mid < hi: always inside the window
        if a[mid] < x:
            lo = mid + 1            # x can only be right of mid
        elif a[mid] > x:
            hi = mid                # x can only be left of mid; mid leaves, since hi is not in the window
        else:
            return mid
    return -1                       # the window is empty: x isn't in a

Traced on a = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] looking for the missing 24 (the animation above):

lo=0 hi=10 mid=5 a[mid]=23  23 < 24: lo = mid + 1
lo=6 hi=10 mid=8 a[mid]=72  72 > 24: hi = mid
lo=6 hi=8 mid=7 a[mid]=56  56 > 24: hi = mid
lo=6 hi=7 mid=6 a[mid]=38  38 > 24: hi = mid
final window: lo=6 hi=6 (lo == hi: True)
-1

The window ends empty at position 6, and 6 is where 24 would go to keep the list sorted. Lesson 3 uses exactly that.

Why it always stops

Every round either returns or throws mid out of the window. mid is inside the window, so the window loses at least one element per round. A window of n elements can’t shrink forever: after at most n rounds it’s empty. (Halving makes it far fewer, lesson 1’s log₂ n + 1, but “it shrinks every round” is all you need to know it ends.)

Three classic bugs

Each one changes a single line of the code above. These are real runs:

The changeWhat breaksReal result
hi = len(a) - 1 at the startthe last element is never in the windowsearch([1, 3, 5], 5) returns -1
lo = mid instead of mid + 1when mid == lo, nothing moves: an endless loopsearch([1, 3], 5) never returns
while lo <= hi (with hi = len(a))the loop runs on an empty window, mid can be len(a)IndexError

The endless loop, traced: after one round the window is [1, 2), mid is 1, a[1] = 3 < 5, and lo = mid sets lo to 1 again, forever:

lo=0 hi=2 mid=1
lo=1 hi=2 mid=1
lo=1 hi=2 mid=1

All three break one of the rules above: the window must start as the whole list, every round must remove mid, and the loop must stop when the window is empty. When a binary search misbehaves, check each line against the promise.

Try it on your computer

Practical 0 · Your binary search: write search yourself, count its looks on a million numbers, then break it two ways and watch the checker catch each one.

Go deeper: closed windows [lo, hi]

Many textbooks use a closed window: hi = len(a) - 1, both ends included, while lo <= hi, and hi = mid - 1. That is also correct, as long as all four lines agree. The bugs in the table above are what you get from mixing the two conventions: one line written for [lo, hi], the rest for [lo, hi).

This course uses the half-open window for three reasons: it matches Python’s range and slices, the empty window is simply lo == hi, and in lesson 3 the place where the window ends up empty is itself the answer (the insertion point), which a closed window makes awkward to read off.

Go deeper: the midpoint in other languages

In Python, lo + hi can be as big as it likes. In languages with fixed-size integers (Java, C), lo + hi can overflow past the largest value and turn negative on a very large array, so a[mid] fails. This bug sat in Java’s own Arrays.binarySearch for years; Joshua Bloch’s write-up tells the story. The fix there is mid = lo + (hi - lo) / 2, which can’t exceed hi. In Python (lo + hi) // 2 is fine.

Common misunderstandings

  • “hi is the last element.” In [lo, hi), hi is one past the last element in play. That’s why it starts at len(a) and why hi = mid (not mid - 1) is right.
  • “mid should be len(a) // 2.” That’s the middle of the whole list. It must come from lo and hi, the middle of what’s still in play.
  • “With duplicates it returns the first copy.” It returns whichever copy a mid happens to land on. Finding the first or last copy is lesson 3.

Check yourself

1. Window lo = 4, hi = 5. How many elements are in it, and which index is mid? One element, position 4 (hi - lo = 1). mid = (4 + 5) // 2 = 4: the only element in the window, as the rule lo <= mid < hi says it must be.
2. You call search on an empty list. What happens, line by line? lo = 0, hi = len([]) = 0. lo < hi is false before the first round, so the loop never runs and the function returns -1. No special case is needed.
3. A colleague writes hi = mid - 1 but keeps everything else as above. Is search([1, 3, 5], 3) right? And search([1, 3, 5], 1)? The first is right: mid is 1 on the first round, a[1] == 3, found. The second goes wrong: mid = 1, a[1] = 3 > 1, so hi = 0, and the window [0, 0) is empty with 1 still at position 0. Since hi is excluded, hi = mid - 1 throws out mid - 1 as well as mid, and mid - 1 may be the answer. Practical 0 has you try exactly this.

Next: Practical 0 · Your binary search, then 3 · First, last, and where it would go.