Sub topic 7
Proving Each Sort Correct with Loop Invariants
This chapter assumes you can read the bubble, selection, and insertion sort code from the earlier chapters. You should also be comfortable with Python slicing and with assert. Testing a sort on a few arrays shows that it works on those arrays. A loop invariant lets you argue that it works on every array.
What a loop invariant is
A loop invariant is a statement about the program's state that is true at the start of every iteration of a loop. You prove it in three steps:
- Initialization: the statement is true before the first iteration.
- Maintenance: if it is true before an iteration, it is still true before the next one.
- Termination: when the loop ends, the invariant plus the exit condition gives the result you want.
The invariant for a sort has to say two things. It has to say which part of the array is in order, and it has to say that the array is still a rearrangement of the input. All three algorithms here change the array only by swapping or shifting elements, so the rearrangement part holds automatically. The proofs below focus on order.
The three invariants
| Algorithm | Invariant at the start of outer iteration `i` | Why it terminates correctly |
|---|---|---|
| Bubble sort | `a[n-i:]` holds the `i` largest values in sorted order | After `n-1` passes, the last `n-1` positions are final, so `a[0]` is the minimum |
| Selection sort | `a[:i]` holds the `i` smallest values in sorted order | After `n-1` passes, the last element is the maximum and is already in place |
| Insertion sort | `a[:i]` holds the original first `i` elements in sorted order | The loop ends at `i = n`, so `a[:n]` is the whole array, sorted |
Bubble sort maintenance. A pass compares adjacent pairs from the left and always carries the larger value rightward. So the largest value in a[:n-i] ends up at position n-1-i. That value is no larger than anything already in the sorted tail, so the tail grows by one and stays sorted. With the early exit, a pass with no swaps means every adjacent pair is in order, and that alone proves the array is sorted.
Selection sort maintenance. The inner loop finds the minimum of a[i:]. Every value in a[i:] is at least as large as everything in the prefix, so swapping that minimum into position i extends the prefix of smallest values.
Insertion sort maintenance. The inner while loop has its own invariant: every element in a[j+2:i+1] is greater than key, and those elements are the original a[j+1:i] shifted right by one. The loop stops when a[j] <= key or j < 0, so writing key at j + 1 leaves a[:i+1] sorted.
Checking invariants in code
You can turn each invariant into an assert. A violation then fails right where it happens, not later as a wrong output.
def is_sorted(xs):
return all(xs[k] <= xs[k + 1] for k in range(len(xs) - 1))
def selection_sort_checked(a):
target = sorted(a)
n = len(a)
for i in range(n - 1):
assert a[:i] == target[:i] # prefix holds the i smallest, sorted
m = i
for j in range(i + 1, n):
if a[j] < a[m]:
m = j
a[i], a[m] = a[m], a[i]
assert a == target
return a
def insertion_sort_checked(a):
original = list(a)
for i in range(1, len(a)):
# prefix is the original first i elements, sorted
assert a[:i] == sorted(original[:i])
key = a[i]
j = i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j]
j -= 1
a[j + 1] = key
assert is_sorted(a)
return a
print(selection_sort_checked([64, 25, 12, 22, 11])) # [11, 12, 22, 25, 64]
print(insertion_sort_checked([12, 11, 13, 5, 6])) # [5, 6, 11, 12, 13]Common errors
- Invariant too weak. "The prefix is sorted" is not enough for selection sort. It does not rule out a smaller value still sitting in the unsorted part.
- Invariant too strong. Insertion sort's prefix is not made of the smallest values. If you claim it is, the maintenance step fails.
- Checking at the wrong moment. An invariant holds at the start of each iteration. In the middle of a shift,
a[j+1]is a duplicate, and the array is briefly not a rearrangement of the input. - Off-by-one bounds. If bubble sort's inner loop runs to
n - iinstead ofn - 1 - i, it readsa[j + 1]past the end of the unsorted region. The invariant tells you exactly where that region ends.
Exercise
Why can't you use selection sort's invariant ("a[:i] holds the i smallest values") to prove insertion sort correct? Give an input that breaks it.
Show answer
Insertion sort's prefix holds only the original first i elements, rearranged into order. Elements further right have not been examined yet. On [5, 6, 1], the prefix at i = 2 is [5, 6], which is sorted, but the smallest value 1 is not in it. The claim fails, so it cannot serve as insertion sort's invariant.
Exercise
Bubble sort with early exit stops after a pass with no swaps, even when i < n - 1. Which fact justifies stopping, given that the tail invariant covers only the last i + 1 positions?
Show answer
A pass with no swaps found a[j] <= a[j + 1] for every adjacent pair in the unsorted region a[:n-i]. So that region is sorted. The tail invariant says every value in the tail is at least as large as every value in a[:n-i], and the tail is sorted. Together these mean the whole array is sorted.