Binary Search in Python
Chapter 43: Binary Search
4 short lessons, with 3D animations, quizzes and coding tasks.
The lessons
Halving the search: lo, hi and the guessing game
Keep two markers, lo and hi, around the part of a sorted list where the target can still be; look at the middle, and move lo past it or hi before it, until you find the target or the part is empty.
Getting the boundaries right: the first and the last
To find the first position where a sorted list passes a test that goes False … False, True … True, keep lo before the edge and hi on or after it, and close them in until lo == hi, the edge.
Binary search on the answer: the smallest load that is enough
When you can check whether a guess is good enough, and every answer above a good one is also good, binary search the range of possible answers for the smallest good one.
Turned-round lists and sorted grids
The departure board at the bus terminal starts from now, 6 pm: 18:00, 20:00, 22:00, 23:00, then the first buses of tomorrow, 05:00, 06:00, 08:00. The times go up, drop once, and go up again: a sorted list turned round. And in the cinema hall, seats are numbered row after row, 1 to 10 in row A, 11 to 20 in row B, and so on: a grid that is sorted if you read it row by row. Neither is a plain sorted list, but both are sorted enough for binary search, once you see how. A turned-round list: the idea in one sentence. Cut a turned-round sorted list at any middle and at least one half is still in order (the single drop is in the other half); check whether the target lies within that ordered half's first and last values, and keep the half where it can be. Its words: a rotated sorted list is a sorted list cut in two and the parts swapped, like [4, 5, 6, 7, 0, 1, 2]; the values here are all different. Step by step: 1. lo, hi = 0, len(a) - 1; while lo <= hi: mid = (lo + hi) // 2; found? return mid 2. a[lo] <= a[mid]: the left half a[lo..mid] is in order. If a[lo] <= target < a[mid], search left (hi = mid - 1), else right (lo = mid + 1) 3. otherwise the right half a[mid..hi] is in order. If a[mid] < target <= a[hi], search right, else left 4. return -1 when lo > hi The purple bar marks the half that is in order: A sorted grid: the idea in one sentence. When every row goes up and starts above where the row before ends, reading row after row gives one sorted list, so binary search positions 0 to rows × cols − 1, and turn each position into a row and a column with r, c = divmod(i, cols). In a grid with 4 columns, position 6 is row 1, column 2 (6 = 1 × 4 + 2). No list is built: each look works out where the middle is. Why it is correct. Turned round: the list drops only once, so the drop lies in at most one half, and the other half is a plain sorted run. For a sorted run, "is the target between its first and last value?" decides exactly whether it can be there. So each look throws away a half that cannot hold the target, and the invariant of Lesson 43.1 still holds. The grid: reading row by row really is sorted (each row starts above the last row's end), and divmod turns positions into cells one to one, so this is Lesson 43.1's search on a list you never had to build. What it costs. Both halve what is left at every look: O(log n) for a turned-round list, and O(log(rows × cols)) for a grid. A grid of 30 rows and 40 columns (1200 seats) needs at most 11 looks; searching each row with binary search would need about 30 × 6, and checking every seat 1200. Mistakes and edge cases. a[lo] < a[mid] instead of <=: when lo == mid (two items left) the left "half" is one item, which is in order; with < the search looks on the wrong side open and closed ends: a[lo] <= target < a[mid] is "from a[lo] up to just before a[mid]"; a[mid] was already checked repeated values: with duplicates, a[lo] == a[mid] doesn't tell which half is in order, and the search can go wrong; this lesson's lists have different values the grid: divmod(mid, cols), not rows; and an empty grid has no m[0], so check it first if it can happen