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

Binary Search: a Quick Intro

Tested 2026-11-28 on Debian GNU/Linux 13 (trixie), Raspberry Pi 4 Model B (4 GB, 4 cores, aarch64); no containers or VMs · with Python 3.13.5 · by the fromzero project · CC BY 4.0

Your shop keeps a sorted list of a million order numbers.

Someone types one in that isn’t there. Reading the list from the top, you can only say so after all 1,000,000 numbers: 30.5 ms on the Raspberry Pi this course was written on (best of 7 runs), for every number that’s missing.

Look at the middle instead, and throw away the half it can’t be in. At most 20 looks: 6.3 µs.

That’s binary search: about ten lines, and easy to get subtly wrong. One - 1 too many and it skips the last number; one + 1 missing and it never stops.

This course has you write it yourself from zero, with one rule that tells you why each boundary is what it is.

By the end you’ll be able to:

  • explain why 20 looks are enough for a million items, and when binary search gives wrong answers;
  • write binary search from scratch with the window [lo, hi), and say why each line keeps it correct;
  • find the first and last copy of a value, and where a missing value would go;
  • spot and fix the off-by-one bugs that skip an element or loop forever.

How it works

Each lesson starts from zero with an animated, step-by-step picture (press Play, or step with the arrow keys), then explains in plain words, with optional Go deeper sections. Each practical has you write the code yourself in ~/binary-search-intro/: requirements, a hint, a hidden solution, a “predict first” question and a part where you break it on purpose. One script, ./lab, does the rest:

  • ./lab setup p0 checks your Python; ./lab setup p1 writes the capstone’s one data file, a day of event times. There’s nothing to download, and every program is yours to write.
  • ./lab check pN tells you whether your work is right. It calls your functions in a separate process with a time limit, so an endless loop is reported instead of freezing your terminal. It only reads.
  • ./lab reset pN starts you at a practical with the earlier ones’ solutions in place. It asks first, and moves your files into a new folder rather than deleting them.

All you need is Python 3.9+ and curl on your own computer. No containers, no virtual machines.

Path

LessonPracticalYou’ll be able to
1 · Why halving beats looking everywhereexplain why 20 looks cover a million items, and why the list must be sorted
2 · The window and its promise0 · Your binary searchwrite binary search with [lo, hi), count its reads, find an endless loop
3 · First, last, and where it would go1 · Capstone: range counts from an empty folderwrite the first/last/insertion-point variants and a tool built on them, tested against bisect
What your folder will look like
 ~/binary-search-intro/
 ├── lab           the lab script: ./lab setup|check|reset pN (Practical 0)
 ├── lab.log       every command ./lab ran, with its output
 ├── bsearch.py    your search(a, x) (Practical 0)
 ├── rounds.py     counts how many elements search reads (Practical 0)
 └── ranges/       the capstone (Practical 1)
     ├── events.txt  100,000 sorted event times (./lab setup p1)
     ├── bounds.py   your lower_bound, upper_bound, first, last, insert_at
     └── count.py    how many events between two times

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.

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.

3 · First, last, and where it would go

In one sentence: instead of stopping when it hits x, search for the edge where the list turns from “smaller than x” to “at least x”; that one position gives you the first copy, the last copy, the count, and where a missing value would go.

The problem it solves

Real sorted data repeats. A log sorted by time has many events in the same second; a price list has many items at 8. Lesson 2’s search returns a copy, whichever one a mid lands on. On a = [2, 8, 8, 8, 12, 16, 23, 38, 56, 72], with 8 at positions 1, 2 and 3:

lo=0 hi=10 mid=5 a[mid]=16  16 > 8: hi = mid
lo=0 hi=5 mid=2 a[mid]=8  8 == 8: found
2

Position 2 is the middle copy. That doesn’t answer the usual questions:

  • Where does the first 8 start? (all events from second 8 on)
  • Where does the last one end? (how many items cost 8)
  • The value isn’t there: where would it go, so the list stays sorted?

The idea: search for an edge, not a value

Draw a line through the sorted list: everything left of it is < 8, everything right of it is >= 8. Because the list is sorted there is exactly one such line, and the first position right of it is the first 8, if there is an 8 at all. If there isn’t, it’s where 8 would go.

  values:   2 | 8   8   8   12  16  23  38  56  72
  index:    0 | 1   2   3   4   5   6   7   8   9
       < 8    |   >= 8
              ^ the edge: lower bound = 1

That position is called the lower bound of x: the first index whose value is >= x (or len(a) if every value is smaller). A binary search can find an edge just as it finds a value, and it never needs to stop early.

How it works

Same window as lesson 2, new promise:

Everything left of lo is < x. Everything from hi on is >= x.

At the start nothing is on either side (lo = 0, hi = len(a)), so the promise holds. Each round looks at a[mid] and moves one edge, keeping it true:

a[mid]MoveWhy the promise holds
a[mid] < xlo = mid + 1mid and everything left of it are < x
a[mid] >= xhi = midmid and everything right of it are >= x; mid may be the answer, and it’s kept as hi

There’s no “equal: return” line. Finding an 8 at mid doesn’t mean it’s the first one, so an equal value moves hi like a bigger one does. When the window is empty, lo == hi, and the two halves of the promise meet: left of lo is < x, from lo on is >= x. lo is the edge.

def lower_bound(a, x):
    """First index i with a[i] >= x, or len(a) if there is none."""
    lo, hi = 0, len(a)
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid] < x:
            lo = mid + 1        # mid is too small: the edge is right of it
        else:
            hi = mid            # a[mid] >= x: the edge is at mid or left of it
    return lo                   # lo == hi: the edge

On the list above, looking for 8 (the animation’s rounds 1 to 4):

lo=0 hi=10 mid=5 a[mid]=16  16 >= 8: hi = mid
lo=0 hi=5 mid=2 a[mid]=8  8 >= 8: hi = mid
lo=0 hi=2 mid=1 a[mid]=8  8 >= 8: hi = mid
lo=0 hi=1 mid=0 a[mid]=2  2 < 8: lo = mid + 1
final window: lo=1 hi=1
1

The other edge: upper bound

Move the line one place in the question: everything <= 8 on the left, > 8 on the right. The first index whose value is > x is the upper bound. The code is the same loop with one character changed, a[mid] <= x instead of a[mid] < x, so an equal value now moves lo past it:

lo=0 hi=10 mid=5 a[mid]=16  16 > 8: hi = mid
lo=0 hi=5 mid=2 a[mid]=8  8 <= 8: lo = mid + 1
lo=3 hi=5 mid=4 a[mid]=12  12 > 8: hi = mid
lo=3 hi=4 mid=3 a[mid]=8  8 <= 8: lo = mid + 1
final window: lo=4 hi=4
4

Everything from two edges

The copies of x are exactly the positions from the lower bound up to (not including) the upper bound: a half-open window again, [lower, upper).

You wantFrom the edgesFor 8 here
first copylower, if lower < len(a) and a[lower] == x, else -11
last copyupper - 1, if that’s >= 0 and a[upper - 1] == x, else -13
how manyupper - lower3
where x would golower1

The checks in the first two rows matter when x is missing. For each x on the same list, real runs (the last two columns are Python’s own bisect, below):

       x    lower    upper    first     last   insert    count  bi_left bi_right
       1        0        0       -1       -1        0        0        0        0
       8        1        4        1        3        1        3        1        4
      10        4        4       -1       -1        4        0        4        4
      99       10       10       -1       -1       10        0       10       10

A missing value has lower == upper: zero copies, and the edge is where it would go. That’s the promise lesson 2 made: its search for 24 ended on an empty window at 6, and the lower bound of 24 in that list makes the same four moves and returns 6. Inserting 24 there keeps the list sorted:

[2, 5, 8, 12, 16, 23, 24, 38, 56, 72, 91]
6

Why < here and <= there

Swap them and each gives the other’s answer, with no error:

lower_bound with <=: 4
first with <=: -1
upper_bound with <: 1
last with <: -1

first(a, 8) says 8 isn’t in the list. To choose, ask what an equal value should do. For the first copy, an equal a[mid] might have more copies left of it, so it stays in play: hi = mid (< sends only smaller values right). For the last copy, more copies may be right of it: lo = mid + 1 (<= sends equal values right too).

Both versions agree with Python’s bisect on 10,000 random lists full of repeats; the swapped ones don’t:

lists: 10000  queries: 120000  mismatches: 0
bug_le lower_bound vs bisect_left: queries: 120000  mismatches: 80120

Try it on your computer

The capstone, Practical 1 · Capstone: range counts from an empty folder, has you write lower_bound, upper_bound, first, last and insert_at from an empty folder, then a tool that counts the events between two times with two searches, and swap a < to watch the checker catch it.

Go deeper: Python's bisect module

The standard library has both edges, in C: bisect.bisect_left(a, x) is the lower bound and bisect.bisect_right(a, x) (also called bisect.bisect) the upper bound. The documentation states the same promise as above: for ip = bisect_left(a, x), every element of a[lo:ip] is < x and every element of a[ip:hi] is >= x. Both take optional lo and hi to search part of a list.

Since Python 3.10 they take key=, to search records by one field. The key is applied to the list’s elements, not to x, so you pass the time itself, not a record (lambda e: e[0] is a one-line function that returns the first item of each record):

import bisect
events = [(5, 'boot'), (12, 'login'), (12, 'click'), (30, 'logout'), (41, 'boot')]
bisect.bisect_left(events, 12, key=lambda e: e[0])    # 1: first event at time 12
bisect.bisect_right(events, 12, key=lambda e: e[0])   # 3: first event after 12

bisect.insort(a, x) finds the place and inserts there. The search is fast, but inserting into a Python list shifts everything after it, so the docs say its cost grows in proportion to the list’s length (written O(n)): fine for a list you search often and change rarely. insort puts a new value after its equal copies (it’s insort_right, the upper bound); insort_left puts it before them:

[(8, 'old'), (8, 'new')]
[(8, 'new'), (8, 'old')]
Go deeper: no early exit, and why that's fine

Lesson 2’s search can stop the moment a[mid] == x. The bounds never stop early: they always run until the window is empty. On a million sorted numbers, over 1,009 searches:

lower_bound: queries=1009 min rounds=19 max rounds=20  rounds for x=a[500000]=1000000: 19
search: queries=1009 min rounds=10 max rounds=20  rounds for x=a[500000]=1000000: 1

search stops after one round for the value at the first mid, but over these 1,009 values it never took fewer than 10, and its worst case is the same 20. The bounds cost 19 or 20 rounds every time and in return give an answer that search can’t: the edge. Python’s bisect searches return only the edges; its documentation builds “is x there?” on top of bisect_left, as the first-copy row above does: a[lower] == x.

Common misunderstandings

  • “Lower bound returns -1 when x is missing.” It returns a position in every case, from 0 to len(a): where x is, or where it would go. “Missing” is a separate check, a[i] == x.
  • “len(a) is an error.” It’s the right answer when every value is smaller than x: the edge is after the end. Check i < len(a) before reading a[i].

Check yourself

1. On the list above, what do lower_bound(a, 13) and upper_bound(a, 13) return, and what does that tell you? Both return 5: 12 at position 4 is smaller than 13, and 16 at position 5 is bigger. lower == upper means there are no 13s, and 5 is where 13 would go, between 12 and 16.
2. A log of events is sorted by time. How do you count the events with a time from A up to and including B, with two searches? upper_bound(times, B) - lower_bound(times, A). The lower bound of A is the first event at A or later; the upper bound of B is the first event after B. Everything between them is in range. The capstone builds exactly this.
3. In lower_bound, a colleague writes hi = mid - 1 in the else branch "to skip mid, since we already looked at it". What goes wrong? mid may be the answer: a[mid] >= x, and it could be the first such position. hi = mid keeps it as the edge's candidate. hi = mid - 1 leaves the window [lo, mid - 1), so both mid - 1 and mid are dropped. On the list above it still gets 8 right (1) by luck, but lower_bound(a, 16) returns 4, the 12, instead of 5. It's lesson 2's third Check yourself question in a new place.

Next: Practical 1 · Capstone: range counts from an empty folder.

Practical 0 · Your binary search

Goal: a folder for this course with its lab script, your own search(a, x) using the window [lo, hi), a small tool that counts how many elements it reads on a million numbers, and two bugs you cause on purpose and watch the checker catch.

Time: ~30 minutes. Where: your own computer: files in ~/binary-search-intro/, commands in a terminal in that folder. Needs Python 3.9 or newer and curl. Read lesson 1 and lesson 2 first.

Task 1 · Get the lab

Make the folder everything in this course goes into, and download the course’s lab script into it:

mkdir -p ~/binary-search-intro
cd ~/binary-search-intro
curl -fo lab http://localhost:8800/binary-search-intro/tools/lab
chmod +x lab
./lab setup p0

It prints:

  ✓ Python 3.13.5 (3.9 or newer)
  ✓ nothing to download: you write every file of this course yourself

ready for p0. Next: write bsearch.py (task 2), then ./lab check p0

Your Python version may differ; anything from 3.9 up is fine.

What setup did

Only checked your Python: this course has no given files and no containers. ./lab alone lists what it can do:

CommandWhat it does
./lab check p0imports your bsearch.py and calls search in a separate process with a 10-second limit, so an endless loop is reported instead of freezing your terminal; it only reads your files
./lab reset p0asks first, then moves your bsearch.py and rounds.py into a new folder before-reset-<date>/; nothing is deleted
./lab updatereplaces the lab script with the newest copy from the book

Every command setup, reset and update run goes to lab.log in the folder.

Create ~/binary-search-intro/bsearch.py yourself, with one function:

  • name search(a, x); a is a sorted list (smallest first), possibly empty
  • returns an index i with a[i] == x, or -1 if x isn’t in a
  • uses the window [lo, hi) from lesson 2: lo is in it, hi is not
  • doesn’t slice the list (a[lo:hi] copies it: as much work as a scan) and doesn’t use the bisect module
Hint

Start with the whole list as the window: lo = 0, hi = len(a). Loop while the window isn’t empty. Each round: mid from lo and hi; if a[mid] is too small, lo moves past mid; if it’s too big, hi moves to mid (hi isn’t in the window, so that already leaves mid out). After the loop: not found.

Solution
# ~/binary-search-intro/bsearch.py

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

Try the edges: an empty list, one element found and not found, the first and last of three, and a gap:

python3 -c "from bsearch import search; print(search([], 5), search([7], 7), search([7], 3), search([1, 3, 5], 1), search([1, 3, 5], 5), search([1, 3, 5], 4))"

You should see:

-1 0 -1 0 2 -1

Task 3 · Count the looks

Lesson 1 said at most 20 rounds for a million numbers. Measure it on your own code. Create ~/binary-search-intro/rounds.py:

  • run as python3 rounds.py N X: searches for X in the sorted numbers 0, 1, ..., N-1 with your search
  • prints one line ending with how many times search read an element (a[i])
  • counts with a subclass of list whose __getitem__ adds one to a counter, then reads the element as usual
Hint

class Peek(list): with a class attribute looks = 0 and a __getitem__(self, i) that increments Peek.looks and returns super().__getitem__(i). Peek(range(n)) makes the list. sys.argv[1] and sys.argv[2] are the arguments, as strings: int() them.

Solution
# ~/binary-search-intro/rounds.py
import sys

from bsearch import search


class Peek(list):
    """A list that counts how many times an element is read."""
    looks = 0

    def __getitem__(self, i):
        Peek.looks += 1
        return super().__getitem__(i)


n, x = int(sys.argv[1]), int(sys.argv[2])
a = Peek(range(n))                  # the sorted numbers 0, 1, ..., n-1
r = search(a, x)
print(f"n={n:,} x={x}: result {r}, looked at {Peek.looks} elements")

Predict first: a million numbers take at most 20 rounds. How many reads does rounds.py report for -1 (smaller than all of them)? And for 999999, the last number?

python3 rounds.py 1000000 -1
python3 rounds.py 1000000 999999
What you see
n=1,000,000 x=-1: result -1, looked at 40 elements
n=1,000,000 x=999999: result 999999, looked at 20 elements

40, then 20. Look at the if: for -1, a[mid] < x is false in every one of the 20 rounds, so the elif reads a[mid] a second time: 2 reads a round. 999999 is found in 19 rounds: in each of the first 18, a[mid] < x is true and one read is enough; the last round reads twice before reaching else. To always read once, store it first: v = a[mid], then compare v.

Now double the list:

python3 rounds.py 2000000 -1
n=2,000,000 x=-1: result -1, looked at 42 elements

Twice the numbers, one more round (two more reads).

Task 4 · Break it: one too many

In bsearch.py, change hi = mid to hi = mid - 1. Lesson 2’s Check yourself 3 predicted what happens:

python3 -c "from bsearch import search; print(search([1, 3, 5], 1), search([1, 3, 5], 3), search([1, 3, 5], 5))"
-1 1 2

No error: 1 is reported missing, the others are found. Run the checker and see how it finds the failing input for you (it prints a second FAIL too, on big lists, and ends with 11/13 passed):

./lab check p0
  FAIL right on every list of 0-5 items, for x below, at, between and above the elements
       wrong for a=[10, 20], x=10: returned -1, expected 0

Now find why, in this order:

  1. Take the smallest failing input the checker gave: search([10, 20], 10).
  2. Trace it by hand: lo = 0, hi = 2, mid = 1; a[1] = 20 > 10, so hi = mid - 1 = 0. The window [0, 0) is empty, but 10 is at position 0.
  3. Check the line against the promise: hi is not in the window, so hi = mid already removes mid. mid - 1 throws out position 0 too, where x still could be.

Put hi = mid back.

Task 5 · Break it: never stops

Change lo = mid + 1 to lo = mid, and run the checker:

./lab check p0

After 10 seconds, among its lines (it ends with 7/8 passed: the checks after the stuck call never ran):

  FAIL a call never returned within 10 s: an endless loop?
       last call: search([10], 15)

The checker stopped the process and shows the call it was stuck in. Trace it: lo = 0, hi = 1, mid = 0; a[0] = 10 < 15, so lo = mid = 0. Nothing changed, so the next round is the same round. lo = mid breaks the rule that every round removes mid from the window, and with // rounding down, mid == lo happens whenever the window has one element (or two).

Put lo = mid + 1 back.

Check your work

./lab check p0
13/13 passed
Go deeper: why the checker tries every list of 0 to 5 items

Off-by-one bugs live at the edges: an empty list (the loop must not run), one element (mid == lo), two (where rounding down matters), and x below the first or above the last. The checker searches every sorted list of 0 to 5 items for values below, at, between and above its elements, so the failing case it reports is small enough to trace by hand, as in task 4. Big random lists then catch what’s left.

Next: lesson 3 · First, last, and where it would go.

Practical 1 · Capstone: range counts from an empty folder

Goal: in a new folder ranges/, your own lower_bound, upper_bound, first, last and insert_at, checked against Python’s bisect on thousands of lists full of repeats; then a tool that answers “how many events between A and B?” with two searches. Then you swap one < and break a time’s format on purpose, and watch what each one costs.

Time: ~40 minutes. Where: your own computer: files in ~/binary-search-intro/ranges/, commands in a terminal in that folder. Read lesson 3 first.

cd ~/binary-search-intro
./lab setup p1
  ✓ Python 3.13.5 (3.9 or newer)
  ✓ ranges/events.txt: 100,000 event times from one day, sorted, one per line

ready for p1. Next: write ranges/bounds.py (task 2), then ./lab check p1

Your copy of lab says doesn't know p1 yet? Run ./lab update first. Skipped Practical 0? ./lab reset p1 starts you here with its solution in place.

What setup did

It made the folder ranges/ and wrote events.txt in it: 100,000 times between 08:00:00 and 17:59:59, sorted, made from a fixed random seed, so your file is the same as the one this page was tested on and your counts match it. The data isn’t what this practical teaches; every .py file in ranges/ is yours to write. Run it again and it keeps the events.txt you have.

Task 1 · Look at the data

cd ranges
head -3 events.txt
tail -1 events.txt
wc -l events.txt
08:00:00
08:00:00
08:00:00
17:59:59
100000 events.txt

The same second appears many times: this is exactly the list with repeats that lesson 3 was about.

Each time is a string, HH:MM:SS, always two digits each. Strings of the same fixed width compare like the times they stand for: "09:05:00" < "10:00:00" because "0" < "1", character by character. So you can search the strings as they are, with no conversion. Task 5 shows what happens when the width isn’t fixed.

Task 2 · Write the five functions

Create ~/binary-search-intro/ranges/bounds.py yourself:

FunctionReturns
lower_bound(a, x)the first index i with a[i] >= x, or len(a)
upper_bound(a, x)the first index i with a[i] > x, or len(a)
first(a, x)the index of the first copy of x, or -1
last(a, x)the index of the last copy of x, or -1
insert_at(a, x)where x would go so a stays sorted, before any copies already there
  • the window [lo, hi) and no early exit: each bound runs until the window is empty
  • first, last and insert_at call the bounds; they don’t loop themselves
  • no slicing, no bisect (the checker uses bisect to compare)
Hint

Lesson 3’s “How it works” has lower_bound in full. upper_bound is the same loop with one character changed. For the other three, lesson 3’s table “Everything from two edges”: each is one line plus a check that the index is inside the list and holds x.

Solution
# ~/binary-search-intro/ranges/bounds.py

def lower_bound(a, x):
    """First index i with a[i] >= x, or len(a) if there is none."""
    lo, hi = 0, len(a)
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid] < x:
            lo = mid + 1        # mid is too small: the edge is right of it
        else:
            hi = mid            # a[mid] >= x: the edge is at mid or left of it
    return lo                   # lo == hi: the edge


def upper_bound(a, x):
    """First index i with a[i] > x, or len(a) if there is none."""
    lo, hi = 0, len(a)
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid] <= x:
            lo = mid + 1        # mid is x or smaller: the edge is right of it
        else:
            hi = mid            # a[mid] > x: the edge is at mid or left of it
    return lo


def first(a, x):
    """Index of the first copy of x, or -1."""
    i = lower_bound(a, x)
    return i if i < len(a) and a[i] == x else -1


def last(a, x):
    """Index of the last copy of x, or -1."""
    i = upper_bound(a, x) - 1
    return i if i >= 0 and a[i] == x else -1


def insert_at(a, x):
    """Where x would go so a stays sorted: before any copies of x already there."""
    return lower_bound(a, x)

Try them on lesson 3’s list, for 8 (three copies) and 10 (none):

python3 -c "from bounds import *; a = [2, 8, 8, 8, 12, 16, 23, 38, 56, 72]; print(lower_bound(a, 8), upper_bound(a, 8), first(a, 8), last(a, 8), insert_at(a, 8)); print(first(a, 10), last(a, 10), insert_at(a, 10))"
1 4 1 3 1
-1 -1 4

The same numbers as lesson 3’s table.

Task 3 · Count a range

Create ~/binary-search-intro/ranges/count.py, run as python3 count.py FILE FROM TO:

  • reads the sorted times in FILE into a list, one per line
  • prints one line that starts with the count of times t with FROM <= t <= TO, e.g. 179 events from 09:00:00 to 09:00:59
  • uses two searches from bounds.py, as lesson 3’s Check yourself 2 worked out, and no loop over the list
  • FROM after TO prints a count of 0, never a negative number
  • a time that isn’t HH:MM:SS (9:00:00) stops the program with a message and a non-zero exit status
Hint

from bounds import lower_bound, upper_bound works because count.py sits next to bounds.py. The arguments are sys.argv[1:]. The lower bound of FROM is the first time in range; the upper bound of TO is the first one after it. re.fullmatch(r"\d\d:\d\d:\d\d", t) checks a time’s format; sys.exit("message") stops with status 1. max(0, ...) handles FROM after TO.

Solution
# ~/binary-search-intro/ranges/count.py
import re
import sys

from bounds import lower_bound, upper_bound

if len(sys.argv) != 4:
    sys.exit("usage: python3 count.py FILE FROM TO   (times as HH:MM:SS)")
path, start, end = sys.argv[1:]
for t in (start, end):
    if not re.fullmatch(r"\d\d:\d\d:\d\d", t):
        sys.exit(f"{t} is not HH:MM:SS: write it with two digits each, like 09:05:00")

with open(path) as f:
    times = [line.strip() for line in f]      # already sorted: the file is in time order

n = max(0, upper_bound(times, end) - lower_bound(times, start))
print(f"{n} events from {start} to {end}")

Predict first: the file holds 100,000 events spread over ten hours. About how many fall in the hour from 09:00:00 to 09:59:59?

python3 count.py events.txt 09:00:00 09:59:59
What you see
10099 events from 09:00:00 to 09:59:59

About a tenth, as the spread predicts. Count the same hour another way, with a tool that reads every line:

grep -c '^09:' events.txt
10099

The same number. grep compared every line. Once the list is in memory, your two searches look at 17 positions each at most, though count.py still reads the whole file to build it (Go deeper, below).

One second, FROM equal to TO, counts the copies of that one time (lesson 3: upper - lower):

python3 count.py events.txt 12:00:00 12:00:00
4 events from 12:00:00 to 12:00:00

Task 4 · Break it: one < too many

In bounds.py, in lower_bound only, change if a[mid] < x: to if a[mid] <= x:.

Predict first: what does the same one-second question print now?

python3 count.py events.txt 12:00:00 12:00:00
python3 count.py events.txt 09:00:00 09:59:59
0 events from 12:00:00 to 12:00:00
10098 events from 09:00:00 to 09:59:59

No error, and the hour is off by just one: the single event at exactly 09:00:00. Now the checker:

./lab check p1

Among its lines (the 10 PASS lines are left out):

  FAIL lower_bound agrees with bisect_left: every list of 0-5 items, then 2,000 random lists full of repeats
       lower_bound([10], 10) returned 1, expected 0
  FAIL first agrees with bisect_left: every list of 0-5 items, then 2,000 random lists full of repeats
       first([10], 10) returned -1, expected 0
  FAIL insert_at agrees with bisect_left: every list of 0-5 items, then 2,000 random lists full of repeats
       insert_at([10], 10) returned 1, expected 0
  FAIL count.py 09:00:00 10:00:00 on a 9-line file 08:00,08:00,09:00,09:00,09:00,09:30,10:00,10:00,11:15: 3 (expected 6)
       it printed: 3 events from 09:00:00 to 10:00:00

10/14 passed

Four FAILs from one character: first, insert_at and count.py all call lower_bound, so start with the function the others are built on. Find why, in this order:

  1. Take the smallest failing input: lower_bound([10], 10).
  2. Trace it: lo = 0, hi = 1, mid = 0; a[0] = 10 <= 10, so lo = 1. The window is empty at 1, past the 10.
  3. Ask what an equal value should do: for the lower bound, an equal a[mid] may be the first copy, so it must stay in play (hi = mid). <= sends it away, and lower_bound turns into upper_bound.

Put < back.

Task 5 · Break it: a time without its zero

In count.py, comment out the three lines that check the format (the for, its if and the sys.exit). Then ask for 08:00:00 to 9:59:59, a time anyone might type.

Predict first: with the check gone, what does it count? (Task 1: strings compare character by character.)

python3 count.py events.txt 08:00:00 9:59:59
100000 events from 08:00:00 to 9:59:59

Every event of the day, up to 17:59. The search did exactly what it was asked: as strings, "9:59:59" is bigger than "17:59:59", because the first characters already differ and "9" > "1". A binary search is only as right as the order it searches; the format check is what keeps every string the same width. Put the three lines back and see the refusal:

python3 count.py events.txt 08:00:00 9:59:59
9:59:59 is not HH:MM:SS: write it with two digits each, like 09:05:00

Check your work

cd ~/binary-search-intro
./lab check p1
23/23 passed

It compares your five functions with bisect_left and bisect_right on every list of 0 to 5 items made of 10, 20 and 30, then on 2,000 random lists of up to 60 numbers from 0 to 9 (many repeats), counts how many positions each bound reads on a million items, and runs your count.py on a small file, your events.txt, FROM after TO and 9:00:00, counting how often it calls each bound.

Go deeper: where the time goes

count.py reads the whole file every time it runs, and reading is a scan. To see what each part costs, put this in ranges/timing.py:

import time

from bounds import lower_bound, upper_bound
t0 = time.perf_counter()
with open('events.txt') as f:
    times = [line.strip() for line in f]
t1 = time.perf_counter()
n = upper_bound(times, '09:59:59') - lower_bound(times, '09:00:00')
t2 = time.perf_counter()
k = sum(1 for t in times if '09:00:00' <= t <= '09:59:59')
t3 = time.perf_counter()
print(f"read the file: {(t1-t0)*1000:.1f} ms; two searches: {(t2-t1)*1e6:.1f} us ({n}); one scan of the list: {(t3-t2)*1000:.1f} ms ({k})")

On the machine this course was written on, in one run:

read the file: 38.5 ms; two searches: 51.1 us (10099); one scan of the list: 18.5 ms (10099)

The two searches take about 51 microseconds, the scan about 360 times as long, and reading the file twice as long again. For one question, the file read is the cost. Binary search pays off when the sorted list is loaded once and asked many times: a server holding the day’s events in memory answers each range question in two searches. Your numbers will differ with the machine; the proportions are what to look at.

Next: you’ve built the whole family from an empty folder. Flag anything that was unclear, wrong or too wordy: select it and press Flag.