Sub topic 3
Why Sorting Digit by Digit Works
This chapter assumes you have read the earlier chapters on stable counting sort and LSD radix sort. It also assumes you know Big-O notation and bitwise shifts and masks.
Why Sorting Digit by Digit Works
The invariant is this: after pass i, the array is sorted by the key's lowest i digits. Pass i + 1 sorts by digit i + 1. When two keys differ in that digit, the pass puts them in the right order. When they tie, a stable pass keeps their existing order, and that order is already correct for the lower digits. After the last pass, the array is sorted by every digit.
You can watch the invariant hold by using Python's stable sorted as each pass:
nums = [170, 45, 75, 90, 802, 24, 2, 66]
out = nums
for place in (1, 10, 100):
out = sorted(out, key=lambda x: (x // place) % 10)
print(place, out)
# 100 [2, 24, 45, 66, 75, 90, 170, 802]Radix Sort Cost and Choosing the Digit Size
Suppose keys are w bits wide and each digit is r bits. Then there are d = ⌈w / r⌉ passes and b = 2^r buckets, and the total time is O(d(n + b)). Wider digits mean fewer passes but a bigger count array. A good rule is r ≈ log₂ n, which keeps b close to n. For 32-bit keys, r = 8 gives 4 passes with 256 counters, and those counters fit in L1 cache.
MSD Radix Sort: Most Significant Digit First
MSD radix sort splits the input into buckets by the top digit, then recurses into each bucket on the next digit. It can stop early once a bucket holds a single item or its keys run out. That makes it a natural fit for strings. The cost is recursion and many small buckets, so implementations usually switch to insertion sort for small buckets.
Handling Negative Numbers and Strings
- Signed integers: subtract the minimum so every key is non-negative. For fixed-width integers, you can instead flip the sign bit, which makes two's-complement values sort correctly as unsigned values.
- Strings: use MSD and treat "end of string" as a digit smaller than any character. LSD also works if you pad every string to the same length with that end marker.
When to Use Counting and Radix Sort in Practice
| Situation | Better choice |
|---|---|
| Small integer range k ≤ n | Counting sort |
| Many fixed-width integer keys | LSD radix sort |
| Arbitrary keys or a custom comparator | Comparison sort |
| Small n or tight memory | Comparison sort |
Radix sort needs O(n + b) extra memory. Its scattered writes into the output array can also miss the cache.
Exercise
You sort 1,000,000 unsigned 64-bit keys. Compare r = 8 and r = 16 by number of passes and number of buckets.
Show answer
r = 8 gives 8 passes with 256 buckets. r = 16 gives 4 passes with 65,536 buckets. Since 65,536 is small next to n = 10^6, r = 16 halves the number of passes. It is often faster, unless the larger count array causes cache misses.