Proofs: Sorting
This page proves the claims made in the sorting lessons: that each algorithm sorts correctly, the costs given in the lessons, and the limits that no comparison-based algorithm can break. The proofs use loop invariants and induction, explained in Induction, Correctness and Recurrences. Arrays are indexed from 0 and have elements.
Bubble sort is correct
The bubble sort of the lessons performs passes ; each pass scans from the right end down to position , swapping adjacent elements that are out of order.
Invariant. After pass , the positions hold the smallest elements, in order.
Proof. During pass , the scan carries a minimum of elements[i-1..n-1] to position . From the moment the scan meets a copy of , the element at the current scan position is always equal to : if its left neighbor is larger, they are swapped; if the neighbor is also equal to , the scan simply continues with that copy. Before the pass, by the invariant for , positions hold the smallest elements in order, and the pass never touches them. So after the pass, position holds the smallest of the rest, which is the -th smallest overall. After pass , the first positions hold the smallest in order, and the last position holds the largest: the array is sorted.
The sentinel. If a pass makes no swap, every pair of adjacent elements in elements[i-1..n-1] is in order, so that part is sorted; together with the invariant, the whole array is sorted, and stopping is correct.
Insertion sort is correct
Invariant. Before processing position , the subarray elements[0..i-1] contains the original first elements, in order.
Proof. For , a single element is sorted. When position is processed, the key elements[i] is saved, and the elements of the sorted prefix that are greater than the key are shifted one position to the right, starting from the end, until an element not greater than the key (or the start of the array) is found. The key is written in the gap. The elements to the left of the gap are at most the key, those to its right are greater, and both groups keep their order: elements[0..i] is sorted. At the end () the whole array is sorted.
Because the loop stops at the first element not greater than the key, equal elements are never moved past each other: insertion sort is stable.
Selection sort is correct
Invariant. After iteration , positions hold the smallest elements, in order.
Proof. Iteration finds the minimum of elements[i..n-1] and swaps it into position . By the invariant for , everything before position is smaller than or equal to everything from on, so the minimum of the rest is the -th smallest element. After iteration , the last element is the largest.
The number of comparisons does not depend on the input: .
Adjacent swaps need quadratic time
The bubble sort lesson argues that algorithms that only swap adjacent elements are slow. Here is the proof.
Claim 1. Swapping two adjacent elements changes the number of inversions by exactly one.
Proof. An inversion is a pair of positions with . Swapping and does not change the relative order of any pair except that pair itself. So the number of inversions changes by exactly one: it decreases if they were out of order, and increases otherwise.
A sorted array has no inversions, so any algorithm that only swaps adjacent elements performs at least swaps, where is the number of inversions of the input.
Claim 2. A random permutation of distinct elements has inversions on average.
Proof. Each of the pairs of positions is an inversion in exactly half of the permutations: reversing a permutation turns each inversion into a non-inversion and vice versa. So each pair contributes to the expected count.
Combining both: bubble sort, insertion sort and any other algorithm based on adjacent swaps need swaps on average, not only in the worst case. Efficient algorithms must move elements over long distances, as Mergesort and Quicksort do.
No comparison sort can beat n log n
Claim. Every sorting algorithm that only obtains information by comparing elements needs at least comparisons in the worst case, which is .
Proof. Represent the algorithm, for a fixed , as a decision tree: each internal node is a comparison "is ?", its two children are the two possible outcomes, and each leaf is the moment the algorithm finishes, having determined the order of the input. Two different permutations of distinct elements must reach different leaves, because they require different rearrangements. So the tree has at least leaves. A binary tree of height has at most leaves, so and
using that the largest factors of are each at least . The height is the number of comparisons in the worst case.
The same argument applied to the average depth of the leaves shows that the bound also holds on average. Mergesort, with in the worst case, is therefore asymptotically optimal. Algorithms that do not only compare (for example, those that use the values of integer keys as array indices) are not bound by this limit.
Quicksort's partition is correct
The Quicksort of the lessons hides the pivot at the end of the range and moves two indices, i from the left and j from the right.
Invariant. At every moment, all elements to the left of i are at most the pivot, and all elements to the right of j (and before the hidden pivot) are at least the pivot.
Proof. Initially both regions are empty. The first inner loop advances i over elements at most the pivot, and the second moves j back over elements at least the pivot, which keeps the invariant. When both stop with i < j, elements[i] is greater than the pivot and elements[j] is smaller; swapping them extends both regions. When the indices cross, every element before i is at most the pivot and every element from i on is at least the pivot, so swapping the pivot into position i puts it in its final position.
Quicksort is then correct by strong induction on the size: both recursive calls receive smaller ranges (the pivot is excluded), sort them by the induction hypothesis, and the pivot between them is already in place.
The average cost of Quicksort
Claim. If the pivot is chosen uniformly at random (or the input is a random permutation and the pivot is any fixed position), Quicksort performs on average
comparisons, where .
Proof. Partitioning elements takes comparisons with the pivot. If the pivot ends up at position (each from to with probability ), the two parts have sizes and . So
with . Multiply by , write the same equation for , and subtract:
Dividing by , the quantity satisfies , and since , the sum telescopes into
Multiplying back by gives the formula. We checked it with exact rational arithmetic against the recurrence for every up to 29; for it gives about 24.4 comparisons. Since , the cost is , only 39% above the lower bound.
The median-of-three pivot of the lessons reduces the constant further (to about ) but the analysis is more involved.
Mergesort is correct and costs n log n
Merge. The merge of two sorted halves repeatedly copies the smaller of their first remaining elements. Invariant: the output written so far contains the smallest elements of both halves, in order. Each step preserves it, because the smallest remaining element of the union is the first remaining element of one of the halves. When one half is exhausted, the rest of the other half is copied, and it is already sorted and not smaller than anything written. So the merge is correct. Taking the element of the left half when two are equal makes Mergesort stable.
Cost. Merging elements takes at most comparisons and exactly copies, so , which is by the division formula. The recursion tree has levels and each level copies all elements once.
Errors, suggestions and public questions open a form on GitHub, visible to everyone.