Proofs: Radix sort (LSD)
These are the human proofs of Radix sort (LSD), at full length.
LSD radix sort sorts the items and is stable full
This proof shows: correctness, stability, termination.
Let and let each key be an integer . Write for the digit of , and for the value of its lowest digits. Then with . We use one fact about this split.
Fact. For keys and : if and only if , or and .
Proof. If , then . If , the two values differ by . If , the first case with and swapped gives .
Termination. Let be the largest key (0 for an empty array). The variable starts at 1 and is multiplied by in each pass, so after passes . The test of line L6 is true as soon as . So the loop runs for passes, where if and otherwise is the least integer with . In each case , and pass (for ) runs with , so line L4 sorts by the digit .
Claim. After pass , the array is sorted by , and items with equal are in their input order.
Proof by induction on . We say that the array before pass 0 is "after pass ", and it is sorted by with all items in input order, so the claim holds for .
Assume the claim after pass , for some . Pass is a stable sort by digit . Take two items and with keys and , where is in front of after pass . We show that , and that came first in the input if .
- If : the sort by digit put first, so , and the Fact gives .
- If : the sort is stable, so was also in front of after pass . By the induction hypothesis , and so by the Fact. If , then , and the induction hypothesis says that came first in the input.
Both cases give the claim after pass .
Theorem. RADIX-SORT returns the items of in non-decreasing order of key, and items with equal keys are in their input order.
Proof. Each pass is a counting sort, which returns a permutation of its input, so the result holds the items of . After the last pass , the Claim says that the array is sorted by , stably. Each key is at most , so .