Sub topic 6
Binary Search: Halving the Range
This chapter assumes you can write loops and functions in Python, use zero-based indexing, and read basic Big-O notation. It also assumes you have read the previous chapter, which explained why binary search only works on sorted data.
The core idea
Linear search throws away one candidate per comparison. Binary search throws away about half of the remaining candidates per comparison. Because the list is sorted, one look at the middle element tells you which half cannot contain the target.
Binary search tracks the part of the list that might still hold the target with two indices:
lois the first index still in play.hiis the last index still in play.
This is an inclusive range, [lo, hi]. At the start it covers the whole list, so lo = 0 and hi = len(a) - 1. Each step picks the middle index of that range and compares the element there to the target:
| Comparison | What it tells you | Update |
|---|---|---|
| `a[mid] == target` | Found it | Return `mid` |
| `a[mid] < target` | Target is to the right of `mid` | `lo = mid + 1` |
| `a[mid] > target` | Target is to the left of `mid` | `hi = mid - 1` |
The + 1 and - 1 matter. You have already checked mid, so you leave it out of the new range. When lo passes hi, the range is empty and the target is not in the list.
The implementation
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)) # -1The loop condition is lo <= hi and not lo < hi. When lo == hi, one element is still in the range and you have to check it.
Tracing a search
Searching for 7 in [1, 3, 5, 7, 9, 11]:
| Step | lo | hi | mid | a[mid] | Action |
|---|---|---|---|---|---|
| 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 | Found, return 3 |
Searching for 4, which is not in the list:
| Step | lo | hi | mid | a[mid] | Action |
|---|---|---|---|---|---|
| 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` |
| 4 | 2 | 1 | — | — | `lo > hi`, return -1 |
Where the search stops is useful information. When the target is missing, lo ends at the index where the target would be inserted (here 2, between 3 and 5). A later chapter builds on this to define lower-bound searches.
Common errors
- Infinite loop. If you write
lo = midorhi = midwith an inclusive range, the range can stop shrinking. Withlo = 0, hi = 1,midis 0, andlo = midleaves the range unchanged. - Missing the last element. Using
while lo < hiwith inclusive bounds skips the final single-element range. - Wrong initial
hi. Settinghi = len(a)with an inclusive range letsmidreach an index past the end of the list. - Unsorted input. The code runs without error but can return -1 for values that are in the list.
Exercise
Trace binary_search([2, 4, 6, 8, 10], 10). List lo, hi, and mid for each iteration and give the return value.
Show answer
Step 1: lo=0, hi=4, mid=2, a[2]=6 < 10, so lo=3. Step 2: lo=3, hi=4, mid=3, a[3]=8 < 10, so lo=4. Step 3: lo=4, hi=4, mid=4, a[4]=10, found. Returns 4.
Exercise
A teammate changes the loop condition to while lo < hi and keeps everything else the same. Give an input where the function now returns the wrong answer, and explain why.
Show answer
binary_search([5], 5) returns -1. Initially lo=0 and hi=0, so lo < hi is false and the loop never runs, even though the one remaining element equals the target. With inclusive bounds, the case lo == hi still holds one candidate that has to be checked.