Sub topic 14
When to Use Counting and Radix Sort in Practice
This chapter assumes you have worked through the earlier chapters. You should know how stable counting sort works, how LSD radix sort runs one pass per digit, and the cost formulas O(n + k) and O(d(n + b)). Here we turn those formulas into decisions about real code.
The Three Questions to Ask
A non-comparison sort pays off only when three conditions all hold:
- The keys can be turned into integers or digits. Integers, fixed-width bit patterns and strings over a small alphabet qualify. Keys ordered by a custom comparison function, such as "sort by distance from a point", do not.
- The key range or digit count is small relative to n. Counting sort needs k close to n or smaller. Radix sort needs few passes, d, for the digit size you choose.
- You can afford the extra memory. Both algorithms write into a separate output array of size n, plus a count array of size k or b.
If any answer is no, a well-tuned comparison sort is usually the better choice.
Memory Use
Merge sort also uses O(n) extra space, but quicksort and heapsort sort in place. Counting and radix sort always allocate an output buffer as large as the input. When the input fills most of available RAM, or the code runs on an embedded device, that extra copy can rule them out. The count array adds a further cost. With 16-bit digits, b = 65,536 counters per pass, which matters little for a million records and dominates the cost for a hundred.
Cache Behavior
Comparison sorts like quicksort scan memory mostly in order, which suits CPU caches. The scatter step of counting sort writes to b different output regions at once. When b is small (256 for 8-bit digits), those write positions stay in cache and the passes run fast. When b is large, each write can miss the cache, and a pass that is linear in theory runs slowly in practice. This is why production radix sorts use 8- to 11-bit digits rather than the largest digit that fits in memory.
Constant Factors and Your Language
Asymptotic wins can disappear in an interpreted language. The script below times a pure-Python counting sort against Python's built-in sorted, which is Timsort implemented in C.
import random
import time
def counting_sort_simple(a, k):
counts = [0] * (k + 1)
for x in a:
counts[x] += 1
out = []
for value, c in enumerate(counts):
out.extend([value] * c)
return out
n = 1_000_000
for k in (255, 5_000_000):
data = [random.randint(0, k) for _ in range(n)]
t0 = time.perf_counter()
result = counting_sort_simple(data, k)
t1 = time.perf_counter()
expected = sorted(data)
t2 = time.perf_counter()
assert result == expected
print(f"k={k:>9}: counting {t1 - t0:.3f}s, sorted() {t2 - t1:.3f}s")With k = 255, counting sort is often faster or competitive. With k = 5,000,000, the count array is five times larger than the input, and sorted usually wins. In C, C++, Rust, or on a GPU, radix sort beats comparison sorts on large integer arrays more reliably.
Summary of Trade-offs
| Factor | Counting sort | LSD radix sort | Comparison sort |
|---|---|---|---|
| Time | O(n + k) | O(d(n + b)) | O(n log n) |
| Extra space | O(n + k) | O(n + b) | O(1) to O(n) |
| Key constraint | Small integer range | Fixed-width digits | Any total order |
| Stable | Yes (prefix-sum version) | Yes | Depends on algorithm |
| Typical uses | Grades, ages, byte values | 32/64-bit ints, GPU sorting, suffix arrays | General-purpose code |
Exercise
You must sort 10,000 records by a 64-bit user ID, in a C program with plenty of memory. Should you use counting sort, LSD radix sort with 16-bit digits, or a library comparison sort? Justify your choice using the cost formulas.
Show answer
Counting sort is out because k = 2^64. Radix sort with 16-bit digits needs d = 4 passes with b = 65,536, about 4 × (10,000 + 65,536) ≈ 302,000 steps. That cost is dominated by the count arrays and causes cache misses. A comparison sort needs roughly 10,000 × log2(10,000) ≈ 133,000 comparisons. Choose the library comparison sort. If you still want a radix sort, 8-bit digits give 8 × (10,000 + 256) ≈ 82,000 steps, which is competitive.
Exercise
Why can't LSD radix sort exploit input that is already almost sorted, while Timsort can?
Show answer
LSD radix sort always performs every digit pass and redistributes every element regardless of the existing order. Timsort detects runs that are already ordered and merges them, so it does close to O(n) work on nearly sorted input.