Sub topic 6
Binary Search: Halving the Range
This chapter assumes you can read Python, are comfortable with zero-based indexing and while loops, and have already seen why binary search only works on sorted data. Here the focus is the iterative algorithm itself: how it narrows the search range, how to trace it by hand, and which edge cases a correct implementation must handle. Later chapters cover why it runs in O(log n), how loop invariants prove the boundaries correct, overflow-safe midpoints, and the recursive form.
The Core Idea
Linear search learns very little from each comparison. If a[i] is not the target, it rules out position i and nothing more. In a sorted list, one comparison tells you much more. If the middle element is smaller than the target, then every element to its left is smaller too, so the whole left half can be dropped in one step.
Binary search applies this repeatedly. It tracks a range of indices that might still hold the target, checks the middle of that range, and throws away the half that cannot hold it. The range shrinks until either the middle element matches or the range is empty.
The Search Range
The implementation in this chapter uses an inclusive range [lo, hi]. Both lo and hi are indices that are still candidates, and all of them, including the two endpoints, may hold the target.
- At the start, the whole list is a candidate:
lo = 0,hi = len(a) - 1. - The range is non-empty while
lo <= hi. - When
lo > hi, no candidates remain, so the target is absent.
This convention decides every other detail of the code: the loop condition, how the boundaries move, and what happens on an empty list. If you change one of these and not the others, you get a bug. That is the most common source of binary search errors.
The Iterative Algorithm
def binary_search(a, target):
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == target:
return mid
elif a[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
print(binary_search([1, 3, 5, 7, 9, 11], 7)) # 3
print(binary_search([1, 3, 5, 7, 9, 11], 4)) # -1Each iteration does the following:
- It computes
midas the floor of the average ofloandhi. Becauselo <= hi,midalways lies inside the range. - It compares
a[mid]to the target. There are three possible outcomes. - Equal: the target is found, so the function returns
mid. a[mid] < target: the target, if present, is to the right ofmid.miditself has just been ruled out, so the new range starts atmid + 1.a[mid] > target: the target, if present, is to the left ofmid. The new range ends atmid - 1.
The + 1 and - 1 matter. Under the inclusive convention, mid has already been checked, so leaving it in the range wastes work. Worse, it can stop the range from shrinking at all, as shown below.
Tracing a Successful Search
Search for 7 in a = [1, 3, 5, 7, 9, 11]:
| Step | lo | hi | mid | a[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 5 | 2 | 5 | 5 < 7, so lo = 3 |
| 2 | 3 | 5 | 4 | 9 | 9 > 7, so hi = 3 |
| 3 | 3 | 3 | 3 | 7 | equal, return 3 |
The candidate range goes from 6 elements to 3, then 1. In step 3, lo == hi, so the range holds exactly one index. The <= in the loop condition is what lets that last single-element range get checked.
Tracing an Unsuccessful Search
Search for 4 in the same list:
| Step | lo | hi | mid | a[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 5 | 2 | 5 | 5 > 4, so hi = 1 |
| 2 | 0 | 1 | 0 | 1 | 1 < 4, so lo = 1 |
| 3 | 1 | 1 | 1 | 3 | 3 < 4, so lo = 2 |
| end | 2 | 1 | lo > hi, return -1 |
When the loop exits, lo and hi have crossed: hi = 1 and lo = 2. That position is meaningful. a[hi] is the largest element smaller than the target and a[lo] is the smallest element larger than it, so lo is exactly where 4 would be inserted to keep the list sorted. This function discards that information by returning -1. The lower-bound chapter builds a search that returns it on purpose.
Why the Loop Always Terminates
Every iteration either returns or makes the range strictly smaller. Since lo <= mid <= hi:
lo = mid + 1makeslostrictly larger than before.hi = mid - 1makeshistrictly smaller than before.
The range size hi - lo + 1 therefore drops by at least one each time. In fact it drops by about half. A non-negative integer that keeps decreasing must reach zero, so the loop cannot run forever. The next chapter turns "about half" into an exact bound on the number of iterations.
Edge Cases
A correct implementation should handle these cases without any special-case code. Check each one against the function above:
| Case | Input | What happens |
|---|---|---|
| Empty list | `[]`, any target | `hi = -1`, loop never runs, returns -1 |
| One element, present | `[5]`, 5 | `mid = 0`, match, returns 0 |
| One element, absent | `[5]`, 3 | `hi` becomes -1, returns -1 |
| Target below all | `[1, 3, 5]`, 0 | `hi` moves left until it reaches -1 |
| Target above all | `[1, 3, 5]`, 9 | `lo` moves right until it reaches 3 |
| First or last element | `[1, 3, 5]`, 1 or 5 | found once the range narrows to that end |
No index outside 0..len(a)-1 is ever read. a[mid] is only accessed inside the loop, where lo <= mid <= hi and both ends are valid indices.
Duplicates: Which Index You Get
If the target appears more than once, this function returns whichever copy the midpoints land on first. That is not necessarily the first or last copy:
def binary_search(a, target):
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == target:
return mid
elif a[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
print(binary_search([2, 2, 2, 2, 2], 2)) # 2, the middle copy
print(binary_search([1, 2, 2, 2, 3], 2)) # 2That is fine when you only need to know whether the target is present. If you need the first occurrence, the last occurrence, or a count, use the lower-bound and upper-bound variants covered later.
Common Mistakes
These are the errors that show up most often in binary search code. Each comes from mixing conventions.
| Mistake | Symptom | Why |
|---|---|---|
| `while lo < hi` with inclusive `hi` | Misses the target when the range shrinks to one element | The `lo == hi` range is never checked; `binary_search([5], 5)` returns -1 |
| `lo = mid` instead of `mid + 1` | Infinite loop | When `hi == lo + 1`, `mid == lo`, so `lo` never moves |
| `hi = mid` instead of `mid - 1` with `<=` | Infinite loop | When `lo == hi == mid`, the range never shrinks |
| `hi = len(a)` with inclusive logic | `IndexError` | `mid` can reach `len(a)` and read past the end |
| Running on unsorted input | Wrong answers, no error | Discarding a half is only valid if order guarantees the target is not there |
Testing Against Linear Search
Small hand-picked tests miss boundary bugs. A good check is to compare binary search against a simple reference implementation on many random sorted lists. With duplicates, the two may return different indices, so compare whether the result is valid instead of comparing index values.
import random
def binary_search(a, target):
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == target:
return mid
elif a[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
def check(trials=10000):
for _ in range(trials):
n = random.randint(0, 20)
a = sorted(random.randint(0, 15) for _ in range(n))
target = random.randint(-2, 17)
result = binary_search(a, target)
if target in a:
assert 0 <= result < n and a[result] == target, (a, target, result)
else:
assert result == -1, (a, target, result)
print("all tests passed")
check()The test includes empty lists (n = 0), duplicates (values from a small range), and targets below and above every element. Try one of the mistakes from the table, such as changing <= to <, and the assertion fails within a few trials and prints the failing input.
Exercise
Trace binary_search([2, 4, 6, 8, 10, 12, 14], 13). List lo, hi, and mid for each iteration, and give the final return value and the values of lo and hi when the loop exits.
Show answer
Step 1: lo=0, hi=6, mid=3, a[3]=8 < 13, so lo=4. Step 2: lo=4, hi=6, mid=5, a[5]=12 < 13, so lo=6. Step 3: lo=6, hi=6, mid=6, a[6]=14 > 13, so hi=5. Now lo=6 > hi=5, so the function returns -1. lo=6 is the index where 13 would be inserted to keep the list sorted.
Exercise
A colleague writes the loop as while lo < hi: but keeps lo = 0, hi = len(a) - 1, lo = mid + 1, and hi = mid - 1. Give the smallest input that returns a wrong answer, and explain the fix.
Show answer
binary_search([5], 5) returns -1. With lo = hi = 0, the condition lo < hi is false, so the single candidate is never checked. Under the inclusive convention, a range with lo == hi still holds one element, so the condition must be lo <= hi.
Exercise
Suppose you replace lo = mid + 1 with lo = mid and leave everything else unchanged. Find an input that makes the loop run forever.
Show answer
binary_search([1, 3], 5). lo=0, hi=1, mid=0, a[0]=1 < 5, so lo = mid = 0. The state is unchanged, so the same step repeats forever. Floor division makes mid equal lo whenever hi = lo + 1, so lo has to move past mid for the range to shrink.