Sub topic 8
Getting the Boundaries Right with Loop Invariants
This chapter assumes you have read the iterative binary search from earlier chapters and can read Python. Most binary search bugs are off-by-one errors. They appear as a loop that never ends, a missed element, or an index that goes out of range. A loop invariant gives you a way to rule these bugs out instead of guessing.
What a Loop Invariant Is
A loop invariant is a statement that is true before the loop starts and stays true after every iteration. For binary search, the invariant describes which part of the array could still hold the target.
For the inclusive version, which uses lo, hi = 0, len(a) - 1, the invariant is:
- If the target is anywhere in
a, it is ina[lo..hi], with both ends included. - Equivalently, every index below
loand every index abovehihas already been ruled out.
Each line of the algorithm follows from this statement:
- Initialization.
lo = 0andhi = len(a) - 1cover the whole array, so the invariant holds at the start. - Loop condition. The range
[lo, hi]contains elements as long aslo <= hi. Whenlo > hi, it is empty, and the target is not in the array. - Update. If
a[mid] < target, thenmidand everything to its left are ruled out, solo = mid + 1. Ifa[mid] > target, thenmidand everything to its right are ruled out, sohi = mid - 1.
Checking the Invariant in Code
You can turn the invariant into assertions while debugging. The check below is O(n), so remove it before you use the code for real work.
def binary_search_checked(a, target):
lo, hi = 0, len(a) - 1
while lo <= hi:
# Invariant: target is not in a[:lo] and not in a[hi + 1:]
assert target not in a[:lo] and target not in a[hi + 1:]
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_checked([1, 3, 5, 7, 9], 9)) # 4
print(binary_search_checked([1, 3, 5, 7, 9], 2)) # -1If you change an update rule and an assertion fails, you know exactly which step broke the invariant.
The Half-Open Convention
Many libraries use a half-open range [lo, hi), where hi points one past the last candidate. Because the invariant is different, the rest of the code changes with it:
def binary_search_half_open(a, target):
lo, hi = 0, len(a) # candidates are a[lo:hi]
while lo < hi: # range is non-empty
mid = (lo + hi) // 2
if a[mid] == target:
return mid
elif a[mid] < target:
lo = mid + 1 # mid ruled out
else:
hi = mid # mid ruled out; hi is exclusive
return -1
print(binary_search_half_open([1, 3, 5, 7, 9], 1)) # 0
print(binary_search_half_open([1, 3, 5, 7, 9], 6)) # -1| Convention | Initial `hi` | Loop condition | Shrink from the right |
|---|---|---|---|
| Inclusive `[lo, hi]` | `len(a) - 1` | `lo <= hi` | `hi = mid - 1` |
| Half-open `[lo, hi)` | `len(a)` | `lo < hi` | `hi = mid` |
Common Errors and What They Cause
lo < hiwith an inclusive range. The loop stops while one candidate is still left, so a one-element range is never checked.hi = midwith an inclusive range. Whenlo == hi,midequals both of them and the range never gets smaller. The loop runs forever.lo = midin either convention. Whenhi = lo + 1, integer division givesmid == lo, solonever moves.hi = len(a)withlo <= hi. Eventuallymidcan equallen(a), anda[mid]raises anIndexError.
To check any update rule, ask two questions: is the invariant still true, and did the range get strictly smaller? If both answers are yes, the loop is correct and it ends.
Exercise
A programmer writes an inclusive search with lo, hi = 0, len(a) - 1 and while lo < hi, but keeps lo = mid + 1 and hi = mid - 1. What does it return for a = [5] and target 5, and why?
Show answer
It returns -1. The loop starts with lo = 0 and hi = 0, so lo < hi is false and the body never runs. Under the inclusive invariant, the range [0, 0] still holds one candidate, so the loop condition must be lo <= hi.
Exercise
Trace an inclusive search that uses hi = mid instead of hi = mid - 1, on a = [1, 3] with target 0. What happens?
Show answer
Start with lo = 0 and hi = 1. Then mid = 0, and a[0] = 1 > 0, so hi = 0. Now lo = 0 and hi = 0, so mid = 0 again, a[0] > 0, and hi stays 0. The range never shrinks, so the loop runs forever.