Loop Invariants and the Correctness of Insertion Sort
Testing a sorting function on a hundred inputs tells you it works on those hundred inputs. A correctness proof tells you it works on every input, including the ones nobody thought to try. For algorithms built from loops, the standard proof tool is the loop invariant. This lesson uses it to prove insertion sort correct, completely: the outer loop, the inner loop and the termination of both. Then it proves the merge step of merge sort and shows how an invariant that is too weak lets a broken program pass.
If loop invariants are new to you, read Proving Programs Correct with Invariants first. This lesson assumes the three-part method from there and goes further.
What "sorting correctly" means
Before proving that an algorithm is correct, state precisely what it must do. The sorting problem:
- Input: a sequence of numbers .
- Output: a reordering of the input such that .
Both conditions matter. "Sorted" alone is not enough: the output [0, 0, 0] is sorted, but it is not a correct answer for the input [3, 1, 2]. The output must contain exactly the input values, each as many times as it appeared, which is what "reordering" (a permutation of the input) means. Keep this in mind; a later section shows a bug that slips through when an invariant forgets it.
Insertion sort
Insertion sort grows a sorted prefix of the array one element at a time. At each step it takes the next element, the key, and shifts the larger elements of the prefix one place right until the key's position opens up.
In pseudocode, with 0-based indices and meaning the elements at positions to (as in a Python slice):
INSERTION-SORT(a)
1 for i = 1 to n - 1
2 key = a[i]
3 j = i - 1
4 while j >= 0 and a[j] > key
5 a[j + 1] = a[j] // shift a larger element one place right
6 j = j - 1
7 a[j + 1] = key // drop the key into the gapThe Python version prints the array at the start of each pass of the outer loop, the moments the invariant talks about. They match the animation's "Prefix … is sorted" steps.
def insertion_sort(a):
a = list(a)
for i in range(1, len(a)):
print(f"i = {i}: prefix {a[:i]} sorted, rest {a[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
print(f"done: {a}")
return a
insertion_sort([7, 3, 8, 5, 2, 6])i = 1: prefix [7] sorted, rest [3, 8, 5, 2, 6]
i = 2: prefix [3, 7] sorted, rest [8, 5, 2, 6]
i = 3: prefix [3, 7, 8] sorted, rest [5, 2, 6]
i = 4: prefix [3, 5, 7, 8] sorted, rest [2, 6]
i = 5: prefix [2, 3, 5, 7, 8] sorted, rest [6]
done: [2, 3, 5, 6, 7, 8]
In C++
The same procedure in C++, printing the same trace:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// prints a[lo:hi] like a Python list
string show(const vector<int>& a, size_t lo, size_t hi) {
string s = "[";
for (size_t k = lo; k < hi; k++) {
if (k > lo) s += ", ";
s += to_string(a[k]);
}
return s + "]";
}
void insertion_sort(vector<int>& a) {
int n = (int)a.size();
for (int i = 1; i < n; i++) {
cout << "i = " << i << ": prefix " << show(a, 0, i) << " sorted, rest "
<< show(a, i, n) << "\n";
int key = a[i];
int j = i - 1;
while (j >= 0 && a[j] > key) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = key;
}
cout << "done: " << show(a, 0, n) << "\n";
}
int main() {
vector<int> a = {7, 3, 8, 5, 2, 6};
insertion_sort(a);
}i = 1: prefix [7] sorted, rest [3, 8, 5, 2, 6]
i = 2: prefix [3, 7] sorted, rest [8, 5, 2, 6]
i = 3: prefix [3, 7, 8] sorted, rest [5, 2, 6]
i = 4: prefix [3, 5, 7, 8] sorted, rest [2, 6]
i = 5: prefix [2, 3, 5, 7, 8] sorted, rest [6]
done: [2, 3, 5, 6, 7, 8]
The outer-loop invariant
Invariant (outer loop). At the start of each iteration of the
forloop, with index , the prefix holds exactly the elements that were originally in positions to , in sorted order.
The proof has the usual three parts.
- Initialization. Before the first iteration , so the prefix is , the single original element . A one-element sequence is sorted, and it holds exactly the original first element.
- Maintenance. Suppose the invariant holds at the start of the iteration for . The body moves the elements of that are larger than the key one place right and puts the key in the gap. Afterwards holds the old prefix plus the key, which are exactly the original elements to , and it is sorted. So the invariant holds at the start of the iteration for . This step quietly relies on the inner loop doing its job, which the next section proves.
- Termination. The loop ends when . The invariant then says , the whole array, holds exactly the original elements in sorted order. That is the definition of a correct output.
Notice that the invariant has two halves: "sorted" and "exactly the original elements". Termination needs both, because the problem statement has both.
The inner-loop invariant
The maintenance step said the while loop "makes room for the key". A complete proof gives the inner loop its own invariant. Fix an iteration of the outer loop, and let be the sorted prefix at its start and the key.
Invariant (inner loop). At each test of the
whilecondition, equals and equals , and every element of is greater than .
In words: the prefix is split at a gap at position ; the left part has not moved, the right part has moved one place right, and everything moved is larger than the key.
- Initialization. At the first test . The left part is all of , the right part is empty, and "every element of an empty part is greater than " is true.
- Maintenance. The body runs only when and . It copies to position and decreases by 1. Now is the first element of the right part, and it is greater than , so the invariant holds with the new .
- Termination. The loop stops when or . In both cases every element left of the gap is at most (either there are none, or the largest of them, , is at most because is sorted), and every element right of the gap is greater than . Writing into the gap at position therefore leaves sorted and holding plus . That is exactly what the outer maintenance step needed.
Why both loops stop. The outer loop runs from 1 to . In the inner loop the quantity is a non-negative integer that drops by 1 on every pass, so it cannot go on forever. Such a quantity is called a variant.
Note: The inner invariant says "greater than ", not "at least ". Equal elements are never moved past the key, so two equal values keep their original order. That property is called stability, and the invariant is where it comes from.
Checking invariants while the program runs
A proof is the real guarantee, but writing the invariant as an assert is a cheap way to catch a mistake in either the code or the proof. This version checks both invariants on 3,000 random lists.
import random
from collections import Counter
def insertion_sort_checked(a):
a = list(a)
original = list(a)
for i in range(1, len(a)):
# outer invariant: a[:i] is the original prefix, sorted
assert a[:i] == sorted(original[:i])
key, j = a[i], i - 1
p = a[:i]
while True:
# inner invariant: left part unmoved, right part shifted, all > key
assert a[:j + 1] == p[:j + 1] and a[j + 2:i + 1] == p[j + 1:]
assert all(x > key for x in a[j + 2:i + 1])
if not (j >= 0 and a[j] > key):
break
a[j + 1] = a[j]
j -= 1
a[j + 1] = key
assert a == sorted(a) and Counter(a) == Counter(original)
return a
rng = random.Random(7)
for trial in range(3000):
xs = [rng.randint(0, 9) for _ in range(rng.randint(0, 12))]
assert insertion_sort_checked(xs) == sorted(xs)
print("3000 random lists sorted, every invariant held")3000 random lists sorted, every invariant held
In C++
The same checks in C++, with assert from <cassert>. The random lists come from std::mt19937, so they are not the ones Python draws, but the result line is the same:
#include <algorithm>
#include <cassert>
#include <iostream>
#include <random>
#include <vector>
using namespace std;
vector<int> insertion_sort_checked(vector<int> a) {
const vector<int> original = a;
int n = (int)a.size();
for (int i = 1; i < n; i++) {
// outer invariant: a[0:i] is the original prefix, sorted
vector<int> prefix(original.begin(), original.begin() + i);
sort(prefix.begin(), prefix.end());
assert(equal(prefix.begin(), prefix.end(), a.begin()));
int key = a[i], j = i - 1;
const vector<int> p(a.begin(), a.begin() + i);
while (true) {
// inner invariant: left part unmoved, right part shifted, all > key
assert(equal(a.begin(), a.begin() + j + 1, p.begin()));
assert(equal(a.begin() + j + 2, a.begin() + i + 1, p.begin() + j + 1));
assert(all_of(a.begin() + j + 2, a.begin() + i + 1,
[key](int x) { return x > key; }));
if (!(j >= 0 && a[j] > key)) break;
a[j + 1] = a[j];
j--;
}
a[j + 1] = key;
}
assert(is_sorted(a.begin(), a.end()) &&
is_permutation(a.begin(), a.end(), original.begin(), original.end()));
return a;
}
int main() {
mt19937 rng(7);
uniform_int_distribution<int> value(0, 9), length(0, 12);
for (int trial = 0; trial < 3000; trial++) {
vector<int> xs(length(rng));
for (int& x : xs) x = value(rng);
vector<int> expected = xs;
sort(expected.begin(), expected.end());
assert(insertion_sort_checked(xs) == expected);
}
cout << "3000 random lists sorted, every invariant held\n";
}3000 random lists sorted, every invariant held
The values are drawn from 0 to 9 on purpose, so that many lists contain repeated values, the case where a "greater than" versus "at least" mistake would show.
A second proof: merging two sorted lists
Merge sort's key step merges two sorted lists into one. Its loop has a clean invariant too.
def merge(left, right):
out = []
i = j = 0
# invariant: out holds the len(out) smallest elements of left + right, in
# sorted order, and left[i] and right[j] are the smallest not yet copied
while i < len(left) and j < len(right):
if left[i] <= right[j]:
out.append(left[i]); i += 1
else:
out.append(right[j]); j += 1
print(f"out = {out}")
out += left[i:] + right[j:]
return out
print(merge([1, 4, 6, 9], [2, 3, 7]))out = [1]
out = [1, 2]
out = [1, 2, 3]
out = [1, 2, 3, 4]
out = [1, 2, 3, 4, 6]
out = [1, 2, 3, 4, 6, 7]
[1, 2, 3, 4, 6, 7, 9]
In C++
The merge in C++, printing out after each step:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string show(const vector<int>& a) {
string s = "[";
for (size_t k = 0; k < a.size(); k++) {
if (k > 0) s += ", ";
s += to_string(a[k]);
}
return s + "]";
}
vector<int> merge(const vector<int>& left, const vector<int>& right) {
vector<int> out;
size_t i = 0, j = 0;
// invariant: out holds the out.size() smallest elements of left + right, in
// sorted order, and left[i] and right[j] are the smallest not yet copied
while (i < left.size() && j < right.size()) {
if (left[i] <= right[j]) out.push_back(left[i++]);
else out.push_back(right[j++]);
cout << "out = " << show(out) << "\n";
}
out.insert(out.end(), left.begin() + i, left.end());
out.insert(out.end(), right.begin() + j, right.end());
return out;
}
int main() {
cout << show(merge({1, 4, 6, 9}, {2, 3, 7})) << "\n";
}out = [1]
out = [1, 2]
out = [1, 2, 3]
out = [1, 2, 3, 4]
out = [1, 2, 3, 4, 6]
out = [1, 2, 3, 4, 6, 7]
[1, 2, 3, 4, 6, 7, 9]
- Initialization.
outis empty, andleft[0],right[0]are the smallest elements of their sorted lists. - Maintenance. The smaller of
left[i]andright[j]is the smallest element not yet copied, so appending it keepsoutsorted and still made of the smallest elements. Advancing that index keeps the second half of the invariant. - Termination. The loop ends when one list is used up. Every element left over in the other list is at least as large as everything in
out, and they are already sorted, so appending them completes a sorted merge. The variant islen(left) + len(right) - len(out).
Using <= rather than < takes the element from left on ties. Since left came first in the original array, this keeps merge sort stable, the same idea as in insertion sort.
When the invariant is too weak
An invariant has to be strong enough to give the result at termination. Here is a "sort" with a bug: inside the inner loop it copies the key into the gap instead of the element being shifted. Check it with only the "sorted" half of the invariant, and it passes.
def buggy_sort(a):
a = list(a)
for i in range(1, len(a)):
key, j = a[i], i - 1
while j >= 0 and a[j] > key:
a[j + 1] = key # bug: should be a[j + 1] = a[j]
j -= 1
a[j + 1] = key
assert a[:i + 1] == sorted(a[:i + 1]) # weak invariant: "the prefix is sorted"
return a
xs = [7, 3, 8, 5, 2, 6]
print("weak invariant held, result:", buggy_sort(xs))
print("correct answer: ", sorted(xs))weak invariant held, result: [2, 2, 2, 2, 2, 6]
correct answer: [2, 3, 5, 6, 7, 8]
Every prefix the buggy code builds is sorted, so the weak assertion never fires, yet the values 3, 5, 7 and 8 have been overwritten. The full invariant, "the prefix holds exactly the original elements, sorted", fails on the very first shift. A correctness proof is only as good as the invariant it proves: the invariant must say everything the output specification says.
Test yourself
Why does the outer invariant of insertion sort say that holds exactly the original first elements, and not only that it is sorted?
- Because that makes the proof shorter
- Because the output must be a permutation of the input, and termination needs that half too
- Because sorted prefixes are always permutations
- Because the inner loop needs it to terminate
The inner loop of insertion sort stops when or . What does the inner invariant then guarantee about the gap at position ?
- Every element left of it is at most and every element right of it is greater than
- It is the last position of the array
- It holds the largest element seen so far
- The left part is empty
Which quantity proves that the inner while loop of insertion sort terminates?
- , which grows
- , a non-negative integer that decreases by 1 on every pass
- The key
- The number of inversions in the whole array
In merge, the comparison is left[i] <= right[j]. What would change if it were left[i] < right[j]?
- The result would no longer be sorted
- The loop would not terminate
- On ties the element from
rightwould be taken first, so merge sort would no longer be stable - Nothing at all