Sub topic 11
Radix Sort Cost and Choosing the Digit Size
This chapter assumes you have read the earlier chapters on stable counting sort and LSD radix sort. It also assumes you can use Big-O notation and that you know how bit shifts and masks pull a group of bits out of an integer. The code reuses counting_sort_by_key and radix_sort_lsd from those chapters. Both are repeated here so each script runs on its own.
The goal is a cost formula you can work with. You will use it to choose how many bits go into each digit, and you will see where that formula stops matching real hardware.
The Basic Cost: O(d(n + b))
LSD radix sort runs one stable counting sort for each digit. Say there are:
nkeys to sort,ddigits per key, which is the number of passes,bpossible values per digit, which is the radix or base.
Each pass is a counting sort over n items with keys in 0..b-1. From the counting sort chapter, one pass costs O(n + b). The parts of that cost are:
- Clearing the count array: O(b).
- The histogram pass over the input: O(n).
- The prefix sums over the count array: O(b).
- The scatter pass that writes each item to its slot: O(n).
There are d passes, so the total time is O(d(n + b)). The extra space is O(n + b): one output buffer of size n and one count array of size b. Both get reused on every pass.
Rewriting the Cost in Terms of Bits
You don't pick d and b separately. Your keys have a fixed width of w bits, for example 32 or 64. You choose a digit width of r bits. That choice sets the other two numbers:
b = 2^rd = ⌈w / r⌉
Substituting gives:
T(n) = O(⌈w / r⌉ · (n + 2^r))
This is a trade-off in one variable. A larger r means fewer passes, but the count array grows exponentially. A smaller r keeps the count array tiny, but each extra pass reads and writes all n items again.
The table shows the options for 32-bit keys, with 8-byte counters as Python or a 64-bit C size_t would use.
| Digit width r | Passes d | Buckets b = 2^r | Count array size |
|---|---|---|---|
| 4 | 8 | 16 | 128 B |
| 8 | 4 | 256 | 2 KiB |
| 11 | 3 | 2,048 | 16 KiB |
| 16 | 2 | 65,536 | 512 KiB |
| 32 | 1 | 4,294,967,296 | 32 GiB |
With r = 32, radix sort turns into a single counting sort over the whole key range. That is the range problem from the counting sort chapter, and it explains why digits exist at all.
Finding the Best r Analytically
Treat the cost as (w / r)(n + 2^r) and ask when growing r stops helping.
- When
2^ris much smaller thann, each pass costs aboutn. Raisingrcuts the number of passes and barely changes the cost of a pass, so it helps. - When
2^ris much larger thann, the count array dominates. Each extra bit doubles the cost of a pass but removes only a fraction of a pass, so it hurts.
The balance point is where 2^r ≈ n, which means r ≈ log₂ n. That gives the classic result from CLRS (Cormen, Leiserson, Rivest and Stein's Introduction to Algorithms):
- If
w ≤ ⌊log₂ n⌋, chooser = w. There is one pass,2^w ≤ n, and the cost is O(n). - Otherwise, choose
r = ⌊log₂ n⌋. The cost is O((w / log n) · n) = O(wn / log n).
The second case explains when radix sort beats comparison sorts. Suppose the keys are integers in the range 0..n^c for some constant c. Then w = c log₂ n, and the cost becomes O(cn) = O(n). Radix sort runs in linear time whenever key width grows at most logarithmically with n. A comparison sort still needs Ω(n log n) on the same input.
A Cost Model You Can Run
This script uses the simplified cost d · (n + 2^r) to find the best r for 32-bit keys at several input sizes.
import math
def radix_cost(n, w, r):
"""Model cost of LSD radix sort: d passes, each costing n + 2^r."""
d = math.ceil(w / r)
return d * (n + 2 ** r)
def best_r(n, w):
"""Digit width in bits that minimises the model cost."""
return min(range(1, w + 1), key=lambda r: radix_cost(n, w, r))
w = 32
for n in [100, 10_000, 1_000_000, 100_000_000]:
r = best_r(n, w)
print(f"n={n:>11,} best r={r:>2} passes={math.ceil(w / r)} "
f"cost={radix_cost(n, w, r):,}")
# n= 100 best r= 5 passes=7 cost=924
# n= 10,000 best r=11 passes=3 cost=36,144
# n= 1,000,000 best r=16 passes=2 cost=2,131,072
# n=100,000,000 best r=16 passes=2 cost=200,131,072The model's choice tracks log₂ n: about 6.6 for n = 100, 13.3 for 10,000 and 19.9 for a million. The choice is pulled toward values of r that divide 32 evenly or nearly evenly. Going from r = 11 to r = 13 still needs 3 passes and only makes the count array bigger, so it can never win.
The curve is flat near its minimum and rises steeply on the right. Picking r a little too small costs little. Picking it too large costs a lot.
Where the Model Breaks: Caches
The model counts every operation as equal. Real memory does not behave that way, and the gap shows up most in the scatter step. During scatter, each item goes to the next free slot of its bucket. With b buckets you have b separate write positions moving through the output buffer at once.
- With
r = 8, there are 256 counters taking 2 KiB, plus 256 active write locations. All of this fits easily in L1 cache, which is usually 32 to 48 KiB, and the hardware can keep 256 write streams cached. - With
r = 11, the 16 KiB count array still fits in L1. The 2,048 write streams start to put pressure on L1 and on the TLB, the cache of page-table entries. - With
r = 16, the 512 KiB count array falls out of L1 and often out of L2. The 65,536 scattered write positions cause cache and TLB misses on almost every write.
For that reason, production radix sorts on 32-bit keys almost always use r = 8, which gives 4 passes and byte-aligned digits, or r = 11, which gives 3 passes. The model prefers r = 16 for a million keys. Measured timings on real CPUs usually do not.
Data-Dependent Pass Counts
The radix_sort_lsd from the previous chapter keeps going only while max_val >> shift > 0. Its real pass count is ⌈bits(max) / r⌉, which can be smaller than ⌈w / r⌉. If your 64-bit values never go above 10⁶, which needs 20 bits, then r = 8 takes 3 passes instead of 8. Computing the maximum first costs one O(n) scan and can save several full passes.
Library implementations use another trick. They build the histograms for every digit in a single read of the input, then skip any pass where all items fall into one bucket, because that pass would not change the order.
Measuring It Yourself
This script times the earlier implementation with several digit widths. Python's interpreter overhead hides most cache effects, so expect the trend to look flatter than it would in C. The O(2^r) term is still clearly visible at large r.
import random
import time
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 radix_sort_lsd(a, bits_per_digit=8):
if not a:
return []
mask = (1 << bits_per_digit) - 1
max_val = max(a)
out = list(a)
shift = 0
while (max_val >> shift) > 0:
out = counting_sort_by_key(out, lambda x: (x >> shift) & mask, mask)
shift += bits_per_digit
return out
random.seed(1)
data = [random.getrandbits(32) for _ in range(200_000)]
expected = sorted(data)
for r in [4, 8, 11, 16, 20]:
start = time.perf_counter()
result = radix_sort_lsd(data, r)
elapsed = time.perf_counter() - start
assert result == expected
print(f"r={r:>2} passes={-(-32 // r)} time={elapsed:.3f}s")At r = 20 the count array has over a million entries for 200,000 items. Clearing it and computing prefix sums on every pass costs more than the work on the data itself.
Summary of the Decision
| Situation | Recommended digit width |
|---|---|
| Small n (under a few thousand) | Use a comparison sort. The fixed O(b) cost per pass is not worth paying |
| 32-bit keys, large n | r = 8 (4 passes) or r = 11 (3 passes) |
| 64-bit keys, large n | r = 8 (8 passes) or r = 11 to 16 (6 to 4 passes) and benchmark |
| Small known maximum | Count passes from the actual maximum, not the type width |
| Key range at most n | One counting sort pass (r = w) |
Exercise
You sort n = 1,000,000 64-bit keys. Using the model cost d·(n + 2^r), compare r = 8 with r = 16. Which does the model prefer, and which might be faster on real hardware?
Show answer
For r = 8: d = 8, cost = 8 × (1,000,000 + 256) = 8,002,048. For r = 16: d = 4, cost = 4 × (1,000,000 + 65,536) = 4,262,144. The model prefers r = 16, which does about half the work. On real hardware, though, r = 16 uses a 512 KiB count array and 65,536 scatter streams, which cause cache and TLB misses. r = 8 or r = 11 (6 passes) is often faster in practice, so you need to benchmark.
Exercise
Keys are integers in the range 0 to n³ − 1. Show that LSD radix sort can sort them in O(n) time, and state the digit width you would use.
Show answer
Each key fits in w = ⌈3 log₂ n⌉ bits. Choose r = ⌈log₂ n⌉, so b = 2^r is less than 2n and d = ⌈w / r⌉ is at most 3. The total cost is O(d(n + b)) = O(3 · (n + 2n)) = O(n). Equivalently, write the keys in base n and use 3 base-n digits per key.
Exercise
Why does choosing r = w (a single pass) make radix sort slow for n = 1,000 keys of 32 bits?
Show answer
With r = w = 32, b = 2³² ≈ 4.3 billion, so the single pass costs O(n + b). That cost is dominated by clearing and scanning a 4.3-billion-entry count array, which needs tens of gigabytes of memory, all to sort just 1,000 items. Here 2^r is far larger than n, so the O(b) term dominates. The cost-minimising choice is r ≈ log₂ 1000 ≈ 10.