Sub topic 7
Binary Search: Discarding Half the Input
Binary search is the simplest divide-and-conquer algorithm. It splits the input, solves one half, and throws the other half away. The combine step does nothing. That makes it a clean place to practice two skills from earlier chapters: proving correctness with an invariant, and reading running time off a recurrence.
This chapter assumes you can write and trace loops and recursive functions in Python, read Big-O notation, and follow the recurrence and master theorem material from the previous chapters.
The Idea: One Comparison Rules Out Half
In a sorted list, comparing the target with the middle element tells you which half can still contain the target. The other half cannot, so you discard it. Each step costs O(1) and leaves a problem half the size.
In divide, conquer, combine terms:
| Step | What binary search does |
|---|---|
| Divide | Pick the middle index `mid` of the current range |
| Conquer | Continue in one half only, chosen by comparing `a[mid]` with the target |
| Combine | Nothing; the answer from the half is the answer |
The Implementation
This version keeps a half-open range [lo, hi). lo is included and hi is excluded, so the range is empty exactly when lo == hi.
def binary_search(a, target):
lo, hi = 0, len(a)
while lo < hi:
mid = (lo + hi) // 2
if a[mid] < target:
lo = mid + 1
else:
hi = mid
return lo if lo < len(a) and a[lo] == target else -1
print(binary_search([1, 3, 5, 7, 9], 7)) # 3
print(binary_search([1, 3, 5, 7, 9], 4)) # -1
print(binary_search([], 4)) # -1Here is a trace of searching for 7 in [1, 3, 5, 7, 9]:
| lo | hi | mid | a[mid] | Decision |
|---|---|---|---|---|
| 0 | 5 | 2 | 5 | 5 < 7, so lo = 3 |
| 3 | 5 | 4 | 9 | not < 7, so hi = 4 |
| 3 | 4 | 3 | 7 | not < 7, so hi = 3 |
| 3 | 3 | loop ends, a[3] == 7, return 3 |
The loop does not stop early when a[mid] == target. It keeps narrowing until the range is empty, and lo ends up at the first index whose value is at least the target. That position is called the lower bound. Because of this, the function returns the leftmost match when the list has duplicates:
print(binary_search([2, 4, 4, 4, 8], 4)) # 1Why It Is Correct: The Loop Invariant
You prove binary search correct with an invariant, which is induction on the number of loop iterations. The invariant has two parts:
- Every index
i < lohasa[i] < target. - Every index
i >= hihasa[i] >= target.
Initialization. With lo = 0 and hi = len(a), both statements are about empty sets of indices, so they hold.
Maintenance. Suppose the invariant holds and lo < hi, so lo <= mid < hi. If a[mid] < target, sortedness gives a[i] < target for every i <= mid, so setting lo = mid + 1 keeps part 1 true. Otherwise a[mid] >= target, so every i >= mid has a[i] >= target, and setting hi = mid keeps part 2 true.
Termination. Each iteration shrinks hi - lo by at least one, because mid + 1 > lo and mid < hi. So the loop ends, with lo == hi. The two parts together now say that lo is the first index with a[lo] >= target. If the target is present anywhere, it is at lo. The final check confirms it.
The termination argument rests on lo <= mid < hi. Floor division of (lo + hi) gives that whenever lo < hi. This is the piece people break most often.
Running Time from the Recurrence
Each step does O(1) work and continues on at most half the range:
T(n) = T(n/2) + O(1)
In master theorem terms, a = 1, b = 2, and f(n) = O(1) = Θ(n^(log₂ 1)) = Θ(n⁰). That is the balanced case, so T(n) = Θ(log n). The recursion tree tells you the same thing directly. It is a single path of depth log₂ n with constant work per level.
For n = 1,000,000 that is about 20 comparisons. For n = 10⁹ it is about 30.
A Recursive Version, and a Hidden O(n) Trap
The recursive form matches the paradigm more visibly. Pass indices, not slices:
def lower_bound(a, target, lo=0, hi=None):
if hi is None:
hi = len(a)
if lo >= hi:
return lo
mid = (lo + hi) // 2
if a[mid] < target:
return lower_bound(a, target, mid + 1, hi)
return lower_bound(a, target, lo, mid)
print(lower_bound([1, 3, 5, 7, 9], 6)) # 3A version that recurses on a[mid+1:] or a[:mid] looks equivalent, but each Python slice copies its elements. The recurrence becomes T(n) = T(n/2) + O(n), which solves to O(n). That loses the whole advantage over a linear scan. The recursion depth is only about log₂ n, so the iterative form has no stack-depth benefit here; it just avoids call overhead.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| `lo = mid` instead of `lo = mid + 1` | Infinite loop when `hi == lo + 1`, since `mid == lo` | Exclude `mid` once it is known to be too small |
| Mixing closed `[lo, hi]` and half-open `[lo, hi)` conventions | Misses the last element or reads out of bounds | Pick one convention; match the loop test (`<` vs `<=`) and updates to it |
| Reading `a[lo]` without checking `lo < len(a)` | `IndexError` when target exceeds every element | Guard the final check |
| `(lo + hi) / 2` in Python | `mid` is a float, indexing fails | Use `//` |
| `(lo + hi) / 2` with fixed-width integers (C, Java) | Overflow on huge arrays | Use `lo + (hi - lo) / 2` |
| Running on unsorted data | Wrong answers, no error raised | Sort first, or use a different method |
Using the Standard Library
Python's bisect module implements the same search. bisect_left returns the lower bound, and bisect_right returns the first index whose value is strictly greater than the target.
from bisect import bisect_left, bisect_right
a = [2, 4, 4, 4, 8]
print(bisect_left(a, 4)) # 1
print(bisect_right(a, 4)) # 4
print(bisect_right(a, 4) - bisect_left(a, 4)) # 3 copies of 4In production code, use bisect. Write your own when the search runs over something that is not a list.
Generalizing: Searching on a Monotone Predicate
Binary search does not need a list. It needs a predicate p(x) that is false for small x and true from some point on. The loop finds the first x where p(x) is true, and the same invariant proof applies with "a[i] < target" replaced by "p(i) is false".
def first_true(lo, hi, pred):
# Smallest x in [lo, hi) with pred(x) True, or hi if none.
# pred must be False...False True...True on [lo, hi).
while lo < hi:
mid = (lo + hi) // 2
if pred(mid):
hi = mid
else:
lo = mid + 1
return lo
def isqrt(n):
# Largest x with x * x <= n, for n >= 0
return first_true(0, n + 2, lambda x: x * x > n) - 1
print(isqrt(10)) # 3
print(isqrt(16)) # 4
print(isqrt(0)) # 0This pattern, often called "binary search on the answer", solves problems like the smallest capacity that ships all packages within D days, or the first commit where a test fails (git bisect). If the predicate is not monotone, the result is meaningless, and nothing will warn you.
Exercise
A colleague writes the loop as while lo < hi: mid = (lo + hi) // 2; if a[mid] <= target: lo = mid else: hi = mid - 1. Give a two-element input where it never terminates, and explain why.
Show answer
With a = [1, 2] and target = 1: lo = 0, hi = 1 after... more simply, take any state where hi == lo + 1 and a[lo] <= target, such as a = [5, 6], target = 5, lo = 0, hi = 1. Then mid = 0, a[0] <= 5, so lo = mid = 0, and the state never changes. Floor division makes mid equal lo whenever the range has two candidates, so lo = mid makes no progress. Use mid = (lo + hi + 1) // 2 with that update pattern, or switch to the half-open form with lo = mid + 1.
Exercise
Write the recurrence for a recursive binary search that passes a[:mid] or a[mid + 1:] to each call, and solve it.
Show answer
Slicing copies up to n/2 elements, so T(n) = T(n/2) + Θ(n). The recursion tree has level costs n, n/2, n/4, ..., a geometric series summing to at most 2n. So T(n) = Θ(n). In master theorem terms, a = 1, b = 2, f(n) = n dominates n⁰, so case 3 gives Θ(n).
Exercise
Using first_true, write a function that returns the index of the last occurrence of target in a sorted list a, or -1 if it is absent.
Show answer
Find the first index whose value exceeds the target and step back one: i = first_true(0, len(a), lambda k: a[k] > target) - 1, then return i if i >= 0 and a[i] == target else -1. For a = [2, 4, 4, 4, 8] and target 4 this returns 3.