Sub topic 14
When to Use Counting and Radix Sort in Practice
This chapter assumes you have read the earlier chapters. You should know how stable counting sort and LSD radix sort work, and you should be comfortable with the O(n + k) and O(d(n + b)) cost formulas. You should also know roughly how merge sort, quicksort, and Python's built-in sorted() (Timsort) behave.
The asymptotic story favors radix sort: linear time beats n log n. Real programs run on hardware with caches, memory limits, and interpreter overhead, and many real keys don't fit the integer model cleanly. This chapter covers the factors that decide whether a non-comparison sort is the right choice.
The Questions to Ask First
Before you compare constants, check whether the algorithm applies at all. Counting and radix sort need keys that can be turned into a fixed number of digits, so that the digits sorted from most to least significant give the same order as the keys. Most other limits follow from that requirement.
The thresholds in the diagram are rough guides. You find the real crossover point by measuring on your own data and hardware.
Key Constraints
Keys must be bit patterns whose order you know
A comparison sort only needs a function that answers "is a before b?". That function can do anything: compare case-insensitive strings using locale rules, order dates in different time zones, or rank objects by a computed score. Radix sort can't use such a function. It needs the key itself, broken into digits.
This rules out several common cases:
- Locale-aware string collation, unless you first convert each string to a sort key (for example with
locale.strxfrm) and radix-sort those byte strings. - Keys whose order depends on context or on more than one field, unless you can pack the fields into one integer.
- Arbitrary-precision integers with no upper bound, where the number of digits d grows with the data.
Floating-point keys need a bit transformation
IEEE 754 floats can be radix-sorted after a fixed transformation of their bits. For a non-negative float, setting the sign bit makes it larger than every transformed negative. For a negative float, flipping all bits reverses its order, which puts more negative values first. The result is an unsigned integer whose order matches the float order. NaN values need separate handling.
import struct
def float_to_key(x):
"""Map a 64-bit float to an unsigned int with the same ordering (no NaNs)."""
bits = struct.unpack(">Q", struct.pack(">d", x))[0]
if bits >> 63: # negative: flip every bit
return bits ^ 0xFFFFFFFFFFFFFFFF
return bits | (1 << 63) # non-negative: set the sign bit
values = [3.5, -0.25, 0.0, -7.0, 1e-300, 2.0, -1e300]
print(sorted(values, key=float_to_key) == sorted(values)) # TrueAfter this mapping, an LSD radix sort with 8 bit digits sorts doubles in 8 passes. GPU sorting libraries sort floats this way.
Packing multiple fields into one key
You can sort by (department, salary) by building one integer key: dept << 32 | salary, provided salary fits in 32 bits. Each field must be non-negative and fixed width. For a descending field, store max_value - field instead. The other option is to run one stable sort per field, from the least significant field to the most significant. That is the same idea as LSD radix sort, applied at the field level.
Memory Use
| Algorithm | Extra memory | Notes |
|---|---|---|
| Counting sort | O(n + k) | Output array plus a count array of size k + 1 |
| LSD radix sort | O(n + b) | One output buffer of n items, reused each pass, plus 2^bits counters |
| MSD radix sort (in place, "American flag" style) | O(b · d) | Counters per recursion level; output is not stable |
| Quicksort / introsort | O(log n) | Recursion stack only |
| Merge sort / Timsort | O(n) | Merge buffer |
| Heapsort | O(1) | Fully in place |
LSD radix sort needs a full second buffer. For 1 GB of 64-bit keys, that is another 1 GB. In memory-tight settings such as embedded systems or very large in-memory datasets, an in-place quicksort may be the only option even if it is slower.
Counting sort's cost depends on k. Sorting a million 32-bit values with plain counting sort needs 2^32 counters, which is 16 GB at 4 bytes each, so it is out of the question. Sorting a million exam scores from 0 to 100 needs 101 counters, which is close to free.
Cache Behavior
On modern CPUs, memory access patterns often matter more than operation counts.
The count array should fit in L1 cache
Each pass increments counts[digit] once per element, in an unpredictable order. With 8 bit digits, the array has 256 entries, about 1 to 2 KB, and stays in the L1 cache (typically 32 to 48 KB per core). With 16 bit digits, the array has 65,536 entries, 256 KB at 4 bytes each, and spills into L2. Every increment then costs several times more. This is the main reason libraries pick digits of 8 to 11 bits, even though wider digits mean fewer passes.
Scatter writes are the real bottleneck
The placement loop writes each element to one of b output regions. Each region is filled sequentially, but the loop moves between b regions at random. When b is larger than the number of cache lines and TLB entries the CPU can keep active, writes start missing the cache. Quicksort and merge sort mostly stream through memory in order, and hardware prefetchers handle that pattern well. This is why a well-tuned introsort is often competitive with radix sort for n in the tens of thousands, despite doing more operations.
High-performance radix sorts address this with tricks such as:
- Computing histograms for all digits in a single initial pass instead of one per pass.
- Buffering a few elements per bucket in cache-sized blocks before writing them out.
- Skipping a pass when every key has the same digit, which shows up as one count equal to n.
Data Distribution
LSD radix sort does the same work on every input of a given size and width. That has both benefits and costs:
- No bad cases. Unlike plain quicksort, adversarial or skewed inputs can't push it toward O(n²). Its running time is predictable.
- No adaptivity. Timsort finds existing runs and sorts already-sorted data in O(n). Radix sort makes all d passes regardless.
- Small keys in wide types. If 64-bit integers all fall below 1,000, a radix sort that loops over
max_val(as in this tutorial's version) stops after 2 passes. A version that always makes 8 passes wastes 6 of them.
Why Python's `sorted()` Usually Wins in Python
The asymptotic advantage only appears when both algorithms run at the same level of implementation. In CPython, sorted() is written in C, while a radix sort written in pure Python runs each loop iteration through the interpreter. Measure it yourself:
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
def bench(n, max_val):
data = [random.randrange(max_val) for _ in range(n)]
t0 = time.perf_counter()
r1 = radix_sort_lsd(data)
t1 = time.perf_counter()
r2 = sorted(data)
t2 = time.perf_counter()
assert r1 == r2
print(f"n={n:>8} max={max_val:>11} radix={t1 - t0:.3f}s sorted={t2 - t1:.3f}s")
random.seed(1)
for n in (10_000, 100_000, 1_000_000):
bench(n, 2**32)On typical hardware, sorted() is roughly 10 to 50 times faster at every size here. This doesn't contradict the theory. It shows that constant factors from the interpreter outweigh a log n factor of about 20. In Python, radix sort pays off when you use a vectorized library (NumPy's np.sort(kind="stable") uses radix sort for 16-bit and smaller integer types) or when the integer structure gives you a shortcut, such as counting sort over a tiny range with collections.Counter.
Where These Algorithms Are Used
- Counting sort: bucketing records by a small enumeration (status codes, grades, days of the week), as a step inside radix sort, and in suffix array construction where the alphabet is small.
- LSD radix sort: large arrays of fixed-width integers or floats, GPU sorting, sorting keys in database and analytics engines, and building spatial indexes from Morton codes.
- MSD radix sort: string sorting, where it reads only the distinguishing prefix of each key, and hybrid sorts that switch to insertion sort for small buckets.
- Comparison sorts: everything else, including small arrays, custom orderings, nearly sorted data, and memory-tight settings.
Summary of Trade-offs
| Factor | Favors radix / counting | Favors comparison sort |
|---|---|---|
| Key type | Fixed-width integers, floats, packed fields | Custom comparators, collation, unbounded keys |
| Input size | Large n (≥ ~10^5 in compiled code) | Small n |
| Key range | Small k (counting) or few digits (radix) | Wide, sparse keys with few elements |
| Memory | Extra O(n) buffer is acceptable | Must sort in place |
| Input order | Random or adversarial | Already or nearly sorted |
| Runtime | Compiled or vectorized code | Pure interpreted code against a built-in sort |
Exercise
You need to sort 50 million 32-bit unsigned integers in C++. You are choosing between 8 bit digits and 16 bit digits for LSD radix sort. Count the passes for each choice and explain which one is likely faster in practice.
Show answer
8 bit digits need 4 passes with a 256-entry count array (about 1 KB), which fits in L1 cache. 16 bit digits need 2 passes, but the count array has 65,536 entries (256 KB at 4 bytes), which spills into L2, and each pass scatters writes across 65,536 output regions, far more than the cache and TLB can track. The 16 bit version moves the data half as many times, but its random increments and scatter writes miss the cache far more often, so 8 bit (or 11 bit, 3 passes) digits are usually faster. Benchmark to confirm.
Exercise
A log-processing job sorts 2 million records by HTTP status code (values 100 to 599) and must keep records with the same code in timestamp order, which is their current order. Which algorithm fits best, and how much extra memory does it need beyond the output array?
Show answer
Stable counting sort by key, with the key shifted to status − 100 so k = 499. It runs in O(n + k) time, it is stable so timestamp order is kept within each code, and it needs only 500 counters beyond the output array. A radix sort or comparison sort would do more work for no benefit.
Exercise
A colleague replaces sorted(user_ids) in a Python service with a pure-Python LSD radix sort because "radix sort is O(n)". Response times get worse. Give two reasons, and suggest a better approach if sorting really is the bottleneck.
Show answer
First, sorted() runs in C while the radix sort runs every loop iteration through the interpreter, and that constant-factor gap (often 10 to 50 times) is much larger than the log n factor radix sort saves. Second, Timsort adapts to existing runs, so if the IDs are partly sorted, sorted() does close to O(n) work while radix sort still makes every pass. If sorting is truly the bottleneck, store the IDs in a NumPy integer array and use np.sort, or move the hot path into compiled code.