Sub topic 10
Why Sorting Digit by Digit Works
The previous chapter built LSD radix sort, which runs one stable counting sort per digit, starting with the least significant digit. The procedure can look backwards. The last pass looks only at the most significant digit, so why does the final array end up ordered by the whole number? This chapter proves that it does. It also shows exactly where the proof breaks if you drop stability or process the digits in the other order.
This chapter assumes you have read the earlier chapters on stability, stable counting sort, and LSD radix sort. You should also be comfortable with proof by induction and with writing a number in base b.
The Claim in Precise Terms
Write each key x as d digits in base b:
x = x[d-1]·b^(d-1) + ... + x[1]·b + x[0], with each 0 ≤ x[i] < b.
Here x[0] is the least significant digit. Pass j, counting from 1, stably sorts by digit x[j-1].
Comparing two numbers with the same number of digits works like comparing words in a dictionary. You look at the most significant digit first. The first position where the two numbers differ decides which is smaller. Ordering numbers by value is the same as ordering their digit tuples (x[d-1], ..., x[1], x[0]) lexicographically. The proof uses this fact directly.
After all d passes, x mod b^d = x, because every key is less than b^d. The array is therefore sorted by the full key.
A Worked Trace
Take the keys [32, 13, 31, 23, 12] in base 10, so d = 2.
| Pass | Sorts by | Result | Low digits seen so far | Sorted by those? |
|---|---|---|---|---|
| start | nothing | 32, 13, 31, 23, 12 | none | yes (no digits seen) |
| 1 | ones digit | 31, 32, 12, 13, 23 | 1, 2, 2, 3, 3 | yes |
| 2 | tens digit | 12, 13, 23, 31, 32 | 12, 13, 23, 31, 32 | yes |
Look at pass 2. The values 12 and 13 share the tens digit 1, so the tens pass sees them as equal. They come out as 12 then 13 only because pass 1 had already put 12 before 13 and the stable pass 2 kept that order. The same thing happens for 31 and 32. The earlier pass breaks the ties that the later pass leaves open.
The Proof by Induction
Let L_j(x) = x mod b^j, the value of the lowest j digits of x.
Base case, j = 0. L_0(x) = 0 for every x, so any array is sorted by L_0.
Inductive step. Assume that after pass j the array is sorted by L_j. Pass j+1 stably sorts by digit x[j]. Note that
L_(j+1)(x) = x[j]·b^j + L_j(x), where 0 ≤ L_j(x) < b^j.
Take any two elements where x ends up before y after pass j+1. There are two cases.
x[j] < y[j]. Thenx[j]·b^j + L_j(x) ≤ x[j]·b^j + (b^j − 1) < y[j]·b^j ≤ L_(j+1)(y). The higher digit dominates whatever the lower digits are.x[j] = y[j]. The pass saw these two as tied. Because the pass is stable,xwas also beforeyafter passj. By the inductive hypothesis,L_j(x) ≤ L_j(y). Adding the samex[j]·b^jto both sides givesL_(j+1)(x) ≤ L_(j+1)(y).
The case x[j] > y[j] cannot happen, because pass j+1 sorted by x[j]. In every possible case L_(j+1)(x) ≤ L_(j+1)(y), so the array is sorted by L_(j+1). ∎
Only case 2 uses stability. That is the one place where the algorithm relies on what earlier passes did. Without stability, an unstable pass may reorder tied elements however it likes, and the work of the earlier passes is lost.
Seeing the Invariant in Code
The program below runs LSD radix sort in base 10 and checks the invariant after every pass. It also has a deliberately broken mode. In that mode the counting sort places tied keys in reverse input order. Every pass still sorts correctly by its own digit, but the passes are not stable.
def counting_sort_by_key(items, key, k, stable=True):
"""Sort items by key(item) in 0..k. If stable=False, ties come out reversed."""
counts = [0] * (k + 1)
for item in items:
counts[key(item)] += 1
total = 0
for v in range(k + 1):
counts[v], total = total, total + counts[v]
out = [None] * len(items)
source = items if stable else list(reversed(items))
for item in source:
kv = key(item)
out[counts[kv]] = item
counts[kv] += 1
return out
def lsd_with_check(a, base=10, stable=True):
"""LSD radix sort that reports whether the invariant holds after each pass."""
if not a:
return []
d = 1
while base ** d <= max(a):
d += 1
out = list(a)
for j in range(d):
p = base ** j
out = counting_sort_by_key(out, lambda x: (x // p) % base, base - 1, stable)
low = [x % (p * base) for x in out]
print(f"pass {j + 1}: {out} sorted by low {j + 1} digit(s): {low == sorted(low)}")
return out
data = [32, 13, 31, 23, 12]
print("stable passes:")
lsd_with_check(data)
print("unstable passes:")
lsd_with_check(data, stable=False)Output:
stable passes:
pass 1: [31, 32, 12, 13, 23] sorted by low 1 digit(s): True
pass 2: [12, 13, 23, 31, 32] sorted by low 2 digit(s): True
unstable passes:
pass 1: [31, 12, 32, 23, 13] sorted by low 1 digit(s): True
pass 2: [13, 12, 23, 32, 31] sorted by low 2 digit(s): FalseThe unstable version passes the check after pass 1, because nothing came before it to preserve. It fails at pass 2. The values 12 and 13 tie on the tens digit, the reversal swaps them, and the ones-digit order from pass 1 is gone.
Why the Order of Passes Matters
Suppose you keep the stable passes but run them from the most significant digit down. Apply the same proof. The last pass now decides the primary order, and the earlier passes only break its ties. The array ends up sorted mainly by the least significant digit.
On [32, 13, 31, 23, 12], a stable tens-digit pass gives 13, 12, 23, 32, 31. A stable ones-digit pass on that gives 31, 12, 32, 13, 23. The result is sorted by the ones digit, with ties broken by the tens digit. That order is correct for the reversed digit tuples and wrong for the numbers.
The general rule is: with stable passes, the last pass is the primary key. LSD radix sort works because it saves the most important digit for last. MSD radix sort, covered in the next chapter, starts with the most significant digit. To make that work, it splits the data into separate buckets and sorts each bucket on its own, instead of making full passes over the whole array.
Edge Cases the Proof Covers
The proof never uses the actual size of a digit or how many keys there are, so several edge cases follow from it directly.
- Keys with fewer digits. In base 10, the key 7 is just
07. Its missing high digits are zeros, and the proof treats them like any other digit. - Extra passes. If you run more passes than needed, every key has digit 0 in the extra positions. A stable sort on a constant key leaves the array unchanged, so the result is still correct, though the extra passes waste time.
- Too few passes. If you stop after
j < dpasses, the invariant guarantees only that the array is sorted byx mod b^j. This is a real bug that appears when the pass count is computed from the wrong value. One common case is counting the digits of the first element instead of the maximum. - Any stable per-digit sort. The proof needs each pass to be stable and correct on its digit. Counting sort is the usual choice because it runs in linear time, but a stable merge sort on each digit would also give a correct result, only more slowly.
- Records, not just numbers. Each pass moves whole records, so attached data travels with its key. This works for the same reason that sorting a table by a secondary field and then stably by the primary field orders it by (primary, secondary). Python's stable
sortedrelies on the same principle when you sort several times on different fields.
Exercise
You run LSD radix sort in base 16 on 32-bit unsigned keys, but a bug stops it after 6 of the 8 passes. Exactly what order does the output have?
Show answer
By the invariant, the output is sorted by x mod 16^6, which is the low 24 bits of each key. The top 8 bits have no effect on the order, so keys that differ only in their top byte can appear in any relative order.
Exercise
In the inductive step, case 1 shows L(j+1)(x) < L(j+1)(y) whenever x[j] < y[j]. Which property of the lower digits makes this true, and would it still hold if a digit could take the value b?
Show answer
It holds because L_j(x) ≤ b^j − 1, so the lower digits together are always smaller than one unit of digit j. If a digit could equal b, the lower part could reach b^j or more. A higher digit would then no longer dominate the lower ones, and the proof would fail.
Exercise
Run stable passes on [21, 12, 22, 11] in base 10, first on the tens digit and then on the ones digit. What is the result, and what key is it actually sorted by?
Show answer
The tens pass gives [12, 11, 21, 22]. The ones pass gives [11, 21, 12, 22]. The result is sorted by (ones digit, tens digit), because the last pass becomes the primary key. It is not sorted by value.