TExcelTAD
Home › Sorting & Order Statistics › Radix Sort

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

text
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 - 1

Digit tt of a non-negative integer xx is ⌊x/baset⌋ mod base\lfloor x / \text{base}^t \rfloor \bmod \text{base}; a number with fewer digits has digit 0 in the missing places.

python · try it yourself
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 503503 and 908908, 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++

cpp · try it yourself
#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 tt (for t=1,…,dt = 1, \ldots, d), the array is sorted by the number formed by the last tt digits of each key, and keys whose last tt digits are equal appear in their original input order.

Proof by induction on tt. For t=1t = 1, pass 1 is a stable sort by digit 0, which is exactly the claim. Suppose the claim holds after pass tt, and consider pass t+1t + 1, a stable sort by digit tt. Take any two keys xx and yy, and compare them by their last t+1t + 1 digits.

  • If their digit tt differs, pass t+1t + 1 puts them in the order of that digit, which is the order of their last t+1t + 1 digits, whatever the earlier passes did.
  • If their digit tt is equal, pass t+1t + 1 keeps them in the order they had before it (stability), which by the induction hypothesis is the order of their last tt digits, and therefore of their last t+1t + 1 digits.

Either way the pair is in the right order, so the array is sorted by the last t+1t + 1 digits. After pass dd it is sorted by all dd digits, which is the whole key.

The second case is where stability is used, and it is essential. With an unstable digit sort, pass t+1t + 1 may scramble keys that agree on digit tt, 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:

python · try it yourself
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 k=basek = \text{base}, so dd passes cost

T=Θ(d (n+base)).T = \Theta\bigl(d\,(n + \text{base})\bigr).

For keys with a fixed number of digits and a fixed base this is Θ(n)\Theta(n). 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 bb-bit keys into digits of rr bits each: there are d=⌈b/r⌉d = \lceil b/r \rceil digits, each with 2r2^r values, so

T(n,b,r)=Θ(br (n+2r)).T(n, b, r) = \Theta\left(\frac{b}{r}\,(n + 2^r)\right).
  • Small rr means many cheap passes; large rr means few passes but a large counter array.
  • The balance point is 2r≈n2^r \approx n: choosing r=⌊lg⁡n⌋r = \lfloor \lg n \rfloor (when b>lg⁡nb > \lg n) gives Θ(b nlg⁡n)\Theta\left(\frac{b\,n}{\lg n}\right). With rr any smaller, the factor b/rb/r grows; with rr larger, the 2r2^r term grows faster than the passes shrink.
  • If b≤lg⁡nb \le \lg n, a single pass with r=br = b is best, and radix sort is just counting sort: Θ(n)\Theta(n).

The program evaluates ⌈b/r⌉(n+2r)\lceil b/r \rceil (n + 2^r), the number of elementary steps, for 32-bit keys:

python · try it yourself
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 nn but stays at or below lg⁡n\lg n. The number of passes ⌈b/r⌉\lceil b/r \rceil changes only at a few values of rr (32 bits split as 4×84 \times 8, 3×113 \times 11 or 2×162 \times 16), so the best choice is the smallest rr for the number of passes that nn can afford, the point where 2r2^r is still at most about nn. 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?

Θ(n)\Theta(n) against Θ(nlg⁡n)\Theta(n \lg n) 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 1.39lg⁡n1.39 \lg n passes' worth of comparisons, but in place and with very cache-friendly access. For n=106n = 10^6, lg⁡n≈20\lg n \approx 20, 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 Θ(n)\Theta(n) 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?

  1. To keep the running time linear
  2. Keys that tie on the current digit must keep the order the earlier passes gave them, or those passes are undone
  3. Because counting sort is always stable
  4. It does not need to be

What does LSD radix sort cost for nn keys of dd digits in base kk?

  1. Θ(nlg⁡n)\Theta(n \lg n)
  2. Θ(d(n+k))\Theta(d(n + k))
  3. Θ(nd)\Theta(n^d)
  4. Θ(nk)\Theta(nk)

For bb-bit keys with b>lg⁡nb > \lg n, which digit size rr makes radix sort cost Θ(bn/lg⁡n)\Theta(bn / \lg n)?

  1. r=1r = 1
  2. r=br = b
  3. r≈lg⁡nr \approx \lg n
  4. r=br = \sqrt{b}

After two passes of LSD radix sort on three-digit decimal numbers, the array is sorted by...

  1. the first two digits
  2. the last two digits, with ties in input order
  3. the middle digit only
  4. nothing yet