Sub topic 7
Proving Each Sort Correct with Loop Invariants
This chapter assumes you can read Python, follow nested loops over array indices, and remember how bubble, selection, and insertion sort move elements, as covered in the earlier chapters. Here we take each sort and show why it always produces a sorted array, not only on the examples we traced.
What a Loop Invariant Is
A loop invariant is a statement about the program's variables that is true every time execution reaches the loop test. A test can show that a sort works on the inputs you tried. An invariant argument covers every possible input.
An invariant proof has three parts:
- Initialization. The statement holds before the first iteration.
- Maintenance. If it holds before an iteration, it still holds before the next one.
- Termination. When the loop exits, the invariant plus the exit condition gives you the result you wanted.
For sorting, the result has two halves, and beginners often forget the second one:
- The output is in nondecreasing order:
a[k] <= a[k+1]for every validk. - The output is a permutation of the input. It contains the same values, each appearing the same number of times.
A function that writes zeros over the whole array passes the first check and fails the second.
The Permutation Half Comes Almost for Free
All three sorts change the array in only two ways. They swap two elements, or, in insertion sort, they shift elements right and then write the saved key into the gap. A swap never changes which values are present. In insertion sort, the shifting temporarily duplicates one value and the saved key is missing from the array, but the final a[j + 1] = key puts back the value that was overwritten. So every array state at a loop test is a permutation of the input. For the rest of the chapter we treat that as settled and concentrate on order.
Bubble Sort
Here is the bubble sort from the earlier chapter. It has an outer loop over passes i and an inner loop over adjacent pairs j.
Inner Invariant
At the inner loop test with index j, a[j] is the maximum of a[0..j].
- Initialization: when
j = 0, the rangea[0..0]holds one element, and that element is its own maximum. - Maintenance:
a[j]is the largest value ina[0..j]. Ifa[j] > a[j+1], the swap moves that maximum to positionj+1. If not,a[j+1]is already at least as large. In both casesa[j+1]is the maximum ofa[0..j+1]. - Termination: the loop stops at
j = n-1-i, soa[n-1-i]is the maximum ofa[0..n-1-i]. That is the "largest value bubbles to the end" behavior, now stated precisely.
Outer Invariant
At the outer loop test with pass index i, the slice a[n-i:] is sorted, and every element in it is greater than or equal to every element in a[:n-i].
- Initialization: when
i = 0, the slicea[n:]is empty, so the statement holds. - Maintenance: the inner loop's termination result puts the maximum of the unsorted region
a[:n-i]at positionn-1-i. That value is at mosta[n-i](by the second clause), so the sorted tail grows by one position and the second clause still holds. - Termination: the loop ends with
i = n-1, soa[1:]is sorted anda[0]is at most every element in it. The whole array is sorted.
The Early Exit
The early exit adds a second way out of the outer loop. If a pass makes no swaps, then every pair the pass compared already satisfied a[j] <= a[j+1] for j from 0 to n-2-i. Together with the outer invariant for the tail, that covers every adjacent pair in the array, so the array is sorted. The early exit is correct because the invariant and the "no swaps" condition together imply the postcondition, the same way normal termination does.
Selection Sort
Outer Invariant
At the outer loop test with index i, a[:i] is sorted and holds the i smallest values of the input. In other words, every element of a[:i] is at most every element of a[i:].
Inner Invariant
At the inner loop test with index j, a[m] is the minimum of a[i:j].
- Initialization:
m = iandj = i + 1, so the rangea[i:i+1]is one element anda[m]is that element. - Maintenance: if
a[j] < a[m], the code setsm = j. Either way,a[m]is now the minimum ofa[i:j+1]. - Termination: when
j = n,a[m]is the minimum ofa[i:n].
Back in the outer loop, the swap puts that minimum at position i. It is at least as large as everything in a[:i] (by the outer invariant) and at most everything in a[i+1:] (because it was the minimum). So a[:i+1] is sorted and holds the i+1 smallest values. At termination i = n-1, so a[:n-1] holds the n-1 smallest values in order, and the one remaining value must be the largest.
Insertion Sort
Outer Invariant
At the outer loop test with index i, a[:i] is sorted and contains exactly the values that were originally in a[:i].
Compare this with selection sort. Insertion sort's prefix is sorted but makes no claim about being the smallest values. If the last input element is 0, it is not in the prefix until the final iteration. Selection sort's prefix is final. Insertion sort's prefix is only sorted relative to itself. That difference explains why insertion sort can stop doing work early on nearly sorted input while selection sort cannot.
Inner Invariant
The while loop opens a gap and moves it left. At the while test, every element in a[j+2 : i+1] is greater than key, a[:j+1] is still the sorted prefix as it was before this iteration, and the slots from j+2 onward hold the shifted elements in their original order.
- Initialization:
j = i-1, soa[j+2 : i+1]isa[i+1 : i+1], which is empty. - Maintenance: the loop body runs only when
a[j] > key. It copiesa[j]one slot right and decrementsj, so the newly shifted element joins the "greater than key" block. - Termination: the loop stops when
j < 0ora[j] <= key. In both cases, writingkeytoa[j+1]puts it after everything less than or equal to it and before everything greater than it. The prefixa[:i+1]is now sorted.
The exit condition a[j] <= key (the loop continues only on a[j] > key) also proves stability. An element equal to key stops the loop, so key never moves to the left of an earlier equal element.
Summary of the Invariants
| Algorithm | Outer invariant (at index i) | Inner invariant | Key fact used at termination |
|---|---|---|---|
| Bubble | `a[n-i:]` sorted and ≥ everything in `a[:n-i]` | `a[j]` = max of `a[0..j]` | Max of unsorted region lands at `n-1-i` |
| Bubble early exit | same | same | No swaps means every adjacent pair is ordered |
| Selection | `a[:i]` sorted and holds the `i` smallest values | `a[m]` = min of `a[i:j]` | Min of `a[i:]` is swapped to `i` |
| Insertion | `a[:i]` sorted, same values as original `a[:i]` | Shifted block `a[j+2:i+1]` all > `key` | `key` goes between ≤ and > neighbors |
Checking Invariants with Assertions
An invariant you can state, you can also test. The code below adds assert statements for each invariant and runs the three sorts on random inputs with many duplicates. This does not replace the proof. It does catch a wrongly stated invariant fast, because a false invariant usually fails within a few hundred random trials.
import random
from collections import Counter
def is_sorted(xs):
return all(xs[k] <= xs[k + 1] for k in range(len(xs) - 1))
def bubble_sort_checked(a):
original = Counter(a)
n = len(a)
for i in range(n - 1):
tail = a[n - i:]
assert is_sorted(tail)
assert not tail or max(a[:n - i]) <= tail[0]
swapped = False
for j in range(n - 1 - i):
assert a[j] == max(a[:j + 1])
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
swapped = True
if not swapped:
break
assert is_sorted(a) and Counter(a) == original
return a
def selection_sort_checked(a):
original = Counter(a)
n = len(a)
for i in range(n - 1):
assert is_sorted(a[:i])
assert i == 0 or a[i - 1] <= min(a[i:])
m = i
for j in range(i + 1, n):
assert a[m] == min(a[i:j])
if a[j] < a[m]:
m = j
if m != i:
a[i], a[m] = a[m], a[i]
assert is_sorted(a) and Counter(a) == original
return a
def insertion_sort_checked(a):
original_list = list(a)
original = Counter(a)
for i in range(1, len(a)):
assert is_sorted(a[:i])
assert Counter(a[:i]) == Counter(original_list[:i])
key = a[i]
j = i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j]
j -= 1
assert all(x > key for x in a[j + 2:i + 1])
a[j + 1] = key
assert is_sorted(a) and Counter(a) == original
return a
random.seed(1)
for trial in range(1000):
data = [random.randint(0, 9) for _ in range(random.randint(0, 12))]
for sort in (bubble_sort_checked, selection_sort_checked, insertion_sort_checked):
assert sort(list(data)) == sorted(data), (sort.__name__, data)
print("all invariant checks passed")The insertion sort check Counter(a[:i]) == Counter(original_list[:i]) holds because, at the start of iteration i, nothing at index i or beyond has been touched yet.
Common Mistakes
- Stating the invariant at the wrong point. An invariant describes the state at the loop test, before the body runs. If you describe the state after the body, your initialization and termination steps will be off by one iteration.
- Leaving out the permutation half. Without it, "the array is sorted" can be satisfied by an array that has lost data.
- Using a weak invariant. "The prefix is sorted" is enough for insertion sort but not for selection sort or bubble sort. If maintenance fails, add the clause the proof needs.
- Ignoring the loop bounds at termination. For bubble sort, the outer loop stops at
i = n-1, notn. The proof still works because the single remaining element is forced into place. If you get the bounds wrong, the final step of the proof does not follow.
Exercise
Suppose a buggy selection sort uses the outer invariant "a[:i] is sorted" and nothing else. Give a 3-element input where the prefix stays sorted after each pass but the final array is not sorted, assuming the inner loop searches only a[i:i+2] instead of a[i:].
Show answer
Take [2, 3, 1]. When i = 0, the search covers a[0:2] = [2, 3], so the minimum 2 stays at position 0. When i = 1, the search covers a[1:3] = [3, 1], so 1 is swapped to position 1, giving [2, 1, 3]. The prefix a[:1] = [2] was sorted after the first pass, but the final array [2, 1, 3] is not sorted. The missing clause, that a[:i] holds the i smallest values, is exactly what this bug breaks: after the first pass, the prefix [2] did not hold the smallest value, 1.
Exercise
In insertion sort, change the while condition from a[j] > key to a[j] >= key. Which part of the correctness argument still holds, and which property is lost?
Show answer
The array still ends up sorted. The termination step now stops at an element strictly less than key (or at j < 0), and key is placed after it and before elements greater than or equal to it, so the prefix stays sorted. Stability is lost, because key now moves to the left of earlier elements with equal keys.
Exercise
Prove that bubble sort with the early exit is correct on an input that is already sorted, using only the invariant argument (no tracing).
Show answer
Before pass 0, the outer invariant holds because the tail a[n:] is empty. During pass 0, every comparison finds a[j] <= a[j+1], so no swap happens and the pass checks every adjacent pair from j = 0 to n-2. The early exit fires, and "no swaps in a pass that covered all pairs of the unsorted region", together with the empty sorted tail, means every adjacent pair is ordered. The array is sorted, and it is a permutation of the input because it was not changed.