Sub topic 10
Why Sorting Digit by Digit Works
At first, LSD radix sort can look like it works by luck. It sorts by the least important digit first, and each later pass seems to scramble the order the earlier passes built. This chapter shows that it does not scramble that order, and it pins down which property of each pass prevents it.
This chapter assumes you have read the earlier chapters on stability, stable counting sort, and LSD radix sort. It also assumes you are comfortable with proof by induction at an informal level.
The invariant
An invariant is a statement that holds true after every step of an algorithm. For LSD radix sort, number the digits from the right, starting at 1. The invariant is:
After pass i, the list is sorted by the number formed from each key's lowest i digits.
After the last pass, the "lowest d digits" are the whole key, so the list is fully sorted. Everything therefore depends on showing that each pass keeps the invariant true.
The inductive step
Suppose the list is sorted by the low i − 1 digits, and pass i sorts it by digit i. Take any two keys x and y, and compare their low i digits:
- Their digit i values differ. Then digit i alone decides which of the two low-i numbers is smaller. Pass i sorts by exactly that digit, so the two keys land in the right order. Their earlier order does not matter.
- Their digit i values are equal. Then the lower i − 1 digits decide the order, and the list was already sorted by those digits before this pass. A stable sort keeps equal keys in their input order, so
xandykeep that correct relative order.
Case 2 is the only place the proof uses stability, and it cannot work without it. If pass i is unstable, it can reverse two keys whose digit i is equal. That throws away the work of every earlier pass.
A counterexample without stability
Take [21, 12, 22, 11] in base 10.
- Pass 1 sorts by the ones digit:
[21, 11, 12, 22]. - Pass 2 sorts by the tens digit. A stable sort gives
[11, 12, 21, 22], which is correct. - An unstable sort may return
[12, 11, 22, 21]instead. Each of those outputs is correctly sorted by the tens digit, but the list as a whole is wrong.
Checking the invariant in code
The function below asserts the invariant after every pass. It uses base-10 digits so the printed output is easy to follow.
def counting_sort_by_key(items, key, k):
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)
for item in items:
kv = key(item)
out[counts[kv]] = item
counts[kv] += 1
return out
def lsd_trace(a, base=10):
out = list(a)
p = 1
passes = 0
while max(a) // p > 0:
out = counting_sort_by_key(out, lambda x: (x // p) % base, base - 1)
passes += 1
low = [x % (p * base) for x in out]
assert low == sorted(low), "invariant broken"
print(f"after pass {passes}: {out}")
p *= base
return out
lsd_trace([329, 457, 657, 839, 436, 720, 355])
# after pass 1: [720, 355, 436, 457, 657, 329, 839]
# after pass 2: [720, 329, 436, 839, 355, 457, 657]
# after pass 3: [329, 355, 436, 457, 657, 720, 839]After pass 2, the low two digits of the list are 20, 29, 36, 39, 55, 57, 57. They are in order, even though the full keys are not yet sorted.
Why the order of digits matters
The proof also explains why LSD radix sort has to go from the least significant digit to the most significant. The last pass has the final say whenever two keys differ on its digit, so that pass must be the most significant digit. If you run the passes in the other order, the least significant digit decides the final order, and that is wrong.
Exercise
In LSD radix sort, which passes have to be stable? Could the first pass use an unstable sort?
Show answer
Every pass except the first has to be stable. The first pass starts from the arbitrary input order, which carries no sorted information, so reordering equal keys loses nothing. Each later pass depends on stability to keep the order the earlier passes built. If you are sorting records and need the whole sort to be stable, the first pass must be stable too.
Exercise
You run stable counting sort passes on [31, 13, 23, 32], most significant digit first and then the ones digit. What do you get, and why is it wrong?
Show answer
Sorting by the tens digit gives [13, 23, 31, 32]. Sorting that list by the ones digit gives [31, 32, 13, 23]. The ones digit ran last, so it decided the final order even though it is the least significant digit.