Radix Sort
Counting sort is linear only when the keys are small. Radix sort removes that restriction for keys that are made of digits, such as integers in some base, fixed-length strings or dates. It sorts by one digit at a time, using counting sort for each digit, and the surprise is the order: it starts with the least significant digit. After the last pass, on the most significant digit, the array is completely sorted. The reason is the stability proved in Counting Sort and Stability, and the proof is an induction on the number of digits.
This is the same algorithm that sorted punched cards on tabulating machines a century ago, one column per pass. The Radix Sort lesson in the DSA course introduces it informally.
Least significant digit first
RADIX-SORT(a, d, base) // keys have d digits in the given base; digit 0 is the least significant
1 for t = 0 to d - 1
2 stably sort a by digit t // counting sort with k = base - 1Digit of a non-negative integer is ; a number with fewer digits has digit 0 in the missing places.
def counting_sort_by_digit(a, t, base=10):
digit = lambda x: (x // base ** t) % base
c = [0] * base
for x in a:
c[digit(x)] += 1
for v in range(1, base):
c[v] += c[v - 1]
out = [None] * len(a)
for x in reversed(a): # backwards: stable
c[digit(x)] -= 1
out[c[digit(x)]] = x
return out
def radix_sort(a, base=10, trace=False):
d = len(str(max(a))) if base == 10 else None
for t in range(d):
a = counting_sort_by_digit(a, t, base)
if trace:
print(f"after pass {t + 1} (digit {t}):", " ".join(f"{x:03}" for x in a))
return a
nums = [503, 87, 512, 61, 908, 170, 897, 275]
print("input: ", " ".join(f"{x:03}" for x in nums))
print(radix_sort(nums, trace=True))input: 503 087 512 061 908 170 897 275
after pass 1 (digit 0): 170 061 512 503 275 087 897 908
after pass 2 (digit 1): 503 908 512 061 170 275 087 897
after pass 3 (digit 2): 061 087 170 275 503 512 897 908
[61, 87, 170, 275, 503, 512, 897, 908]
Read each pass with the digits already processed in mind. After pass 1 the numbers are ordered by their last digit. After pass 2 they are ordered by their last two digits: among numbers whose tens digits tie, such as and , pass 2 kept the order pass 1 gave them. After pass 3, all three digits. Returning the array after each pass is the practice problem Radix Sort, Pass by Pass.
In C++
#include <cstdio>
#include <vector>
std::vector<int> counting_sort_by_digit(const std::vector<int>& a, int place) { // place = 1, 10, 100, ...
int c[10] = {0};
for (int x : a) ++c[x / place % 10];
for (int v = 1; v < 10; ++v) c[v] += c[v - 1];
std::vector<int> out(a.size());
for (int i = static_cast<int>(a.size()) - 1; i >= 0; --i) out[--c[a[i] / place % 10]] = a[i];
return out;
}
int main() {
std::vector<int> a = {503, 87, 512, 61, 908, 170, 897, 275};
int max = 0;
for (int x : a) if (x > max) max = x;
int pass = 1;
for (int place = 1; max / place > 0; place *= 10, ++pass) {
a = counting_sort_by_digit(a, place);
std::printf("after pass %d:", pass);
for (int x : a) std::printf(" %03d", x);
std::printf("\n");
}
}after pass 1: 170 061 512 503 275 087 897 908
after pass 2: 503 908 512 061 170 275 087 897
after pass 3: 061 087 170 275 503 512 897 908
Correctness: induction on the digits
Claim. After pass (for ), the array is sorted by the number formed by the last digits of each key, and keys whose last digits are equal appear in their original input order.
Proof by induction on . For , pass 1 is a stable sort by digit 0, which is exactly the claim. Suppose the claim holds after pass , and consider pass , a stable sort by digit . Take any two keys and , and compare them by their last digits.
- If their digit differs, pass puts them in the order of that digit, which is the order of their last digits, whatever the earlier passes did.
- If their digit is equal, pass keeps them in the order they had before it (stability), which by the induction hypothesis is the order of their last digits, and therefore of their last digits.
Either way the pair is in the right order, so the array is sorted by the last digits. After pass it is sorted by all digits, which is the whole key.
The second case is where stability is used, and it is essential. With an unstable digit sort, pass may scramble keys that agree on digit , undoing the earlier passes. The program replaces the stable digit sort by one that walks forwards with end-of-block counters, which reverses equal digits:
def digit_sort(a, t, stable):
digit = lambda x: (x // 10 ** t) % 10
c = [0] * 10
for x in a: c[digit(x)] += 1
for v in range(1, 10): c[v] += c[v - 1]
out = [None] * len(a)
for x in (reversed(a) if stable else a): # forwards = equal digits come out reversed
c[digit(x)] -= 1
out[c[digit(x)]] = x
return out
nums = [503, 87, 512, 61, 908, 170, 897, 275]
for stable in [True, False]:
a = list(nums)
for t in range(3):
a = digit_sort(a, t, stable)
print(f"stable digit sorts: {stable!s:5} -> {a} sorted: {a == sorted(nums)}")stable digit sorts: True -> [61, 87, 170, 275, 503, 512, 897, 908] sorted: True
stable digit sorts: False -> [87, 61, 170, 275, 512, 503, 897, 908] sorted: False
Cost, and choosing the digit size
Each pass is a counting sort with , so passes cost
For keys with a fixed number of digits and a fixed base this is . The interesting freedom is in what a digit is. A 32-bit integer can be split into 32 one-bit digits, or 4 eight-bit bytes, or 2 sixteen-bit halves. In general, cut -bit keys into digits of bits each: there are digits, each with values, so
- Small means many cheap passes; large means few passes but a large counter array.
- The balance point is : choosing (when ) gives . With any smaller, the factor grows; with larger, the term grows faster than the passes shrink.
- If , a single pass with is best, and radix sort is just counting sort: .
The program evaluates , the number of elementary steps, for 32-bit keys:
import math
def cost(n, b, r):
return math.ceil(b / r) * (n + 2 ** r)
b = 32
for n in [1000, 100_000, 10_000_000]:
best = min(range(1, b + 1), key=lambda r: cost(n, b, r))
row = ", ".join(f"r={r}: {cost(n, b, r):,}" for r in [1, 4, 8, 11, 16])
print(f"n = {n:>10,}: best r = {best:>2} (lg n = {math.log2(n):4.1f}) | {row}")n = 1,000: best r = 8 (lg n = 10.0) | r=1: 32,064, r=4: 8,128, r=8: 5,024, r=11: 9,144, r=16: 133,072
n = 100,000: best r = 11 (lg n = 16.6) | r=1: 3,200,064, r=4: 800,128, r=8: 401,024, r=11: 306,144, r=16: 331,072
n = 10,000,000: best r = 16 (lg n = 23.3) | r=1: 320,000,064, r=4: 80,000,128, r=8: 40,001,024, r=11: 30,006,144, r=16: 20,131,072
The best digit size grows with but stays at or below . The number of passes changes only at a few values of (32 bits split as , or ), so the best choice is the smallest for the number of passes that can afford, the point where is still at most about . Real implementations sorting 32-bit integers typically use 8-bit or 11-bit digits, so that the counter array fits in the processor's fastest cache.
Is radix sort better than quicksort?
against looks decisive, but the constant factors are different. With 8-bit digits, radix sort makes 4 passes over 32-bit keys, each pass reading every key and writing it to a new array. Quicksort makes about passes' worth of comparisons, but in place and with very cache-friendly access. For , , so quicksort does roughly 7 times as many basic steps, and each step is cheaper. Which one wins depends on the machine, the key size and the data; radix sort tends to win for large arrays of short integer keys, and it needs extra memory, which quicksort does not.
Radix sort also needs keys that have digits. It sorts integers, fixed-width strings and tuples of small fields (dates as year, month, day) naturally; it does not sort arbitrary objects with a custom comparison, which is all a comparison sort needs.
Test yourself
Why must the per-digit sort in LSD radix sort be stable?
- To keep the running time linear
- Keys that tie on the current digit must keep the order the earlier passes gave them, or those passes are undone
- Because counting sort is always stable
- It does not need to be
What does LSD radix sort cost for keys of digits in base ?
For -bit keys with , which digit size makes radix sort cost ?
After two passes of LSD radix sort on three-digit decimal numbers, the array is sorted by...
- the first two digits
- the last two digits, with ties in input order
- the middle digit only
- nothing yet