Correctness: Invariants & Proofs
Loop invariants, induction and termination: knowing an algorithm works before you run it.
Jon Bentley proved a binary search correct in Programming Pearls, and Joshua Bloch wrote the same loop into Java's standard library. In 2006 Bloch reported that both fail on arrays of more than about a billion elements, because (low + high) / 2 overflows. The proof was sound for mathematical integers, and the program ran on 32-bit ones. This lesson is about proofs that hold, and about stating exactly what they assume.
What you’ll learn
- Write a specification as a precondition and a postcondition, and distinguish partial from total correctness.
- Prove a loop correct with an invariant (initialization, maintenance, termination), and prove that it stops with a variant.
- Prove insertion sort, binary search and Euclid's algorithm correct, and prove recursive algorithms correct by induction.
- Use invariants to write two-pointer, sliding-window and binary-search loops without off-by-one errors, and check them with assertions.
What "correct" means
To prove a program correct you first have to say what correct means. A specification has two parts: a precondition, what the program may assume about its input, and a postcondition, what it promises about its output. For a lower-bound binary search: precondition, the array is sorted; postcondition, the returned index is the first one with , or if there is none.
Two levels of guarantee are standard. Partial correctness: if the program stops, its output satisfies the postcondition. Total correctness: in addition, it always stops. So a correctness proof has two parts, and the second, termination, is the one most often forgotten.
Think first Is a program that never stops partially correct for every specification?
Yes. Partial correctness only constrains the outputs of runs that stop, and this program has none, so it satisfies every postcondition vacuously. That is why total correctness adds termination as a separate obligation.
Loop invariants
A loop invariant is a statement about the program's variables that holds every time control reaches the top of the loop. To use one, prove three things:
- Initialization: it holds before the first iteration.
- Maintenance: if it holds before an iteration, and the loop condition is true, it holds after the iteration.
- Termination: when the loop exits, the invariant together with the negated loop condition implies the postcondition.
This is induction on the number of iterations, with a final step that points at the goal.
def insertion_sort(a):
for j in range(1, len(a)):
# invariant: a[0..j-1] holds the original a[0..j-1], sorted
key = a[j]
i = j - 1
while i >= 0 and a[i] > key: # shift larger keys one slot right
a[i + 1] = a[i]
i -= 1
a[i + 1] = key
# exit: j has reached len(a), so all of a is sorted
return aInitialization (): the prefix is one item, the original , and one item is sorted.
Maintenance. The inner loop shifts each key of the prefix that is larger than
keyone slot right, keeping their order, and stops at the first keykeyor at the left end. Droppingkeyinto the gap at leaves a sorted prefix one longer, holding the original :Termination. The outer loop exits when , and the invariant then says that is the original input, sorted: the postcondition. Both loops stop, since counts up to and counts down to .
Binary search, proved
Binary search is the classic test of writing a loop correctly: Bentley, citing Knuth, notes that the first binary search was published in 1946 but the first one without bugs only in 1962. The cure is to choose the invariant first and derive the code from it. For the lower bound, the first index with , use the half-open range :
def lower_bound(a, x):
"""First index i with a[i] >= x, or len(a). Precondition: a is sorted."""
lo, hi = 0, len(a)
while lo < hi:
# invariant: a[i] < x for all i < lo, and a[i] >= x for all i >= hi
mid = lo + (hi - lo) // 2 # lo <= mid < hi
if a[mid] < x:
lo = mid + 1 # the answer is right of mid
else:
hi = mid # the answer is mid or left of it
return lo # lo == hiThe invariant, for a sorted array:
Initialization: with and both index sets are empty, so it holds vacuously. Maintenance: , so is a real index. If , then for every , and moving to keeps the left half true; otherwise for every , and moving to keeps the right half true.
Termination. The variant is a natural number that strictly decreases, because and ; in fact it at least halves. At exit , and the invariant says that is the first index with .
A variant of lower_bound keeps while lo < hi and mid = lo + (hi - lo) // 2, but sets lo = mid instead of lo = mid + 1 when . What goes wrong?
- It returns an index one too small
- Nothing:
lo = midalso keeps the invariant - It can loop forever: when and ,
midequalsloand the range never shrinks - It overflows on large arrays
Show the answer
C. It can loop forever: when and , mid equals lo and the range never shrinks
The invariant survives, since every still has , but the variant does not: with , mid is , and setting lo = mid changes nothing. Partial correctness holds while total correctness fails, which is exactly why termination needs its own argument.
Termination: variants, and Euclid
A variant, or ranking function, proves termination: a quantity that is a natural number whenever the loop is about to iterate, and that strictly decreases in every iteration. Natural numbers cannot decrease forever, so the loop stops. More generally, any well-founded order, one with no infinite descending chain, will do: pairs compared lexicographically prove that nested or interleaved loops stop.
Euclid's algorithm shows both halves of a proof at work:
def gcd(a, b): # precondition: a, b >= 0, not both 0
while b != 0:
# invariant: gcd(a, b) is the gcd of the original inputs
# variant: b, a natural number
a, b = b, a % b
return a # b == 0, and gcd(a, 0) = aInvariant. With we have . Any that divides and divides , and any that divides and divides . The two pairs have the same common divisors, hence the same greatest one:
Variant. The new second number is , a natural number smaller than , so strictly decreases and the loop stops:
Exit. The loop exits with , and every number divides 0, so the invariant becomes the postcondition:
How many times does the loop body run for gcd(89, 55)?
Show the answer
9
The pairs are (89, 55), (55, 34), (34, 21), (21, 13), (13, 8), (8, 5), (5, 3), (3, 2), (2, 1), and then (1, 0): 9 rounds, every quotient equal to 1. Consecutive Fibonacci numbers are the slowest inputs of their size, which is Lamé's theorem in Euclid's Algorithm in Depth.
Recursion and induction
For a recursive algorithm the invariant becomes an induction hypothesis. To prove f correct on every input, prove it on the base cases, then prove it on an input of size assuming that every recursive call, which works on a smaller input, returns the right answer. Calls on inputs of size about need strong induction, which assumes the claim for all smaller sizes at once.
Claim : on any list of length ,
mergesortreturns a sorted permutation of it. Base cases : the list comes back unchanged, and it is sorted.Inductive step, . The halves have lengths below , so by the induction hypothesis both recursive calls return sorted permutations of their halves:
The merge lemma. Merging sorted lists and keeps the invariant "the output holds the smallest items of and in sorted order, and , are the smallest items not yet output". Taking the smaller of and preserves it, and when both lists are used up the output is all of their items, sorted. So holds.
Recognizing it
Invariants are not only for proofs after the fact: they are the fastest way to write tricky loops correctly. Before coding a two-pointer scan, a sliding window or a binary search, write down what must be true at the top of every iteration, then derive the updates that keep it true. The common patterns:
| Technique | Invariant at the top of each iteration | Why the answer follows |
|---|---|---|
| binary search for a boundary | for ; for | at , the boundary is |
| two pointers, pair sum in a sorted array | no pair that uses an index outside sums to the target | once , no pair is left |
| sliding window, longest valid window | is valid, and is the smallest start that keeps it valid | the longest valid window ending at each is examined |
| Kadane's algorithm | cur is the largest sum of a subarray ending at ; best the largest seen so far | every subarray ends somewhere |
| prefix sums | the sum of is | |
| Dijkstra's algorithm | every settled vertex has its true distance | at the end every reachable vertex is settled |
For pair sum in a sorted array, starts at 0 and at . When you move right. Which invariant justifies that move?
- is sorted
- No pair that uses an index outside sums to
- increases at every step
- Every pair inside has already been checked
Show the answer
B. No pair that uses an index outside sums to
If , then for every , so no pair that uses can work, and discarding keeps the invariant. The case is symmetric. When the pointers meet, the invariant says that no pair sums to .
Testing versus proving. Tests find bugs, but as Dijkstra put it they cannot show their absence. Invariants make tests sharper too: an assert of the invariant inside the loop turns a silent wrong answer into a failure at the very iteration that broke it, and comparing a fast solution with a brute force on thousands of small random inputs, stress testing, catches most of what remains.
Common bugs
- Mixing inclusive and half-open ranges: choose one, and write the invariant in that convention.
- An update that does not shrink the range, such as
lo = midwith a rounded-downmid: an infinite loop. - Forgetting the equal case or duplicates: "the first index with " and "some index with " are different specifications.
- The empty input: the invariant must hold, and the loop must exit, when .
- Arithmetic that overflows fixed-width integers, which no reasoning about mathematical integers will catch.
Key takeaways
- A specification is a precondition and a postcondition; partial correctness says the output is right if the program stops, and total correctness adds that it always stops.
- A loop invariant must hold initially, be preserved by every iteration, and with the negated loop condition imply the postcondition; a variant, a natural number that strictly decreases, proves termination.
- Insertion sort keeps a sorted prefix; binary search keeps " left of , from on" with variant ; Euclid keeps the gcd with variant .
- Recursive algorithms are proved by strong or structural induction: assume correctness on smaller inputs and prove it for the whole.
- A proof is about a model:
(lo + hi) / 2is right for mathematical integers and wrong for 32-bit ones. Tests find bugs; invariants explain why there are none.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A sorting function returns [] for every input. Which part of the specification does it violate?
- The precondition
- "The output is sorted"
- "The output is a permutation of the input"
- Termination
Show the answer
C. "The output is a permutation of the input"
The empty list is sorted and the function always stops; what fails is the clause that the output holds exactly the input's items. A specification without that clause would be satisfied by this useless function.
Which quantity proves that lower_bound, with while lo < hi, terminates?
- , which moves toward the answer
- , a natural number that strictly decreases in every iteration
- , which shrinks
- , which never decreases
Show the answer
B. , a natural number that strictly decreases in every iteration
A variant must be a natural number, or come from a well-founded order, and strictly decrease in every iteration. does, because makes both updates shrink it.
Why can mid = (lo + hi) / 2 break binary search in Java on huge arrays, but never in Python?
- Java's
inthas 32 bits, so can exceed and wrap to a negative number, while Python's integers are unbounded - Python rounds division differently
- Python checks array bounds and Java does not
- Java arrays cannot hold more than a billion elements
Show the answer
A. Java's int has 32 bits, so can exceed and wrap to a negative number, while Python's integers are unbounded
The proof assumed mathematical integers. In 32-bit arithmetic, overflows once it passes , about 2.1 billion, which can happen on arrays of more than about elements. lo + (hi - lo) / 2 computes the same value without the large sum.
To prove by strong induction that merge sort is correct on lists of every length, what may you assume when proving it for length ?
- That it is correct for length only
- That merging is correct, which needs no proof
- That the input is already sorted
- That it is correct on every input shorter than
Show the answer
D. That it is correct on every input shorter than
The halves have lengths and , both smaller than when but not equal to in general, so you need the hypothesis for all smaller lengths: strong induction. The merge's correctness is a separate lemma, with its own loop invariant.
A proposed invariant holds initially and is preserved by every iteration, but at loop exit it does not imply the postcondition. What should you do?
- Nothing: initialization and maintenance are enough
- Strengthen the invariant until, together with the exit condition, it implies the postcondition
- Weaken the postcondition until it follows
- Add more test cases
Show the answer
B. Strengthen the invariant until, together with the exit condition, it implies the postcondition
" is an integer" is an invariant of almost any loop, and useless. A good invariant is strong enough to finish the proof and weak enough to stay true; it usually says what the loop has achieved so far, as in " is sorted".
Go deeper
- Euclid’s Algorithm in Depth · The oldest algorithm: its invariant, Lamé’s bound and the extended GCD.
- Hoare Logic & Verified Algorithms · Preconditions, postconditions, weakest preconditions and machine-checked proofs.
- Correctness in Finite Precision · Integer overflow, floating point and robust predicates: when correct math gives wrong answers.
Further reading
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 2, "Getting Started".
- J. Bentley, Programming Pearls, 2nd ed. (Addison-Wesley, 2000), column 4, "Writing Correct Programs".
- D. Gries, The Science of Programming (Springer, 1981).
- J. Bloch, "Extra, Extra – Read All About It: Nearly All Binary Searches and Mergesorts are Broken," Google Research Blog (2006).