Counting Sort, Radix Sort & Bucket Sort
Beating n log n by never comparing: sorting integers in linear time.
Sorting ten million 32-bit integers by comparisons takes at least comparisons in the worst case. Radix sort needs four counting passes over the data, using each key's bytes as array indices and never comparing two keys. The "barrier" binds only algorithms that learn about keys by comparing them.
What you’ll learn
- Implement stable counting sort with running totals of counts, in time, and explain why its stability matters.
- Implement LSD radix sort, prove it correct by induction on the digits, and choose the digit size: for -bit keys and -bit digits.
- Use MSD radix sort for strings, and bucket sort for uniformly distributed reals in expected time.
- Explain why these sorts escape the bound, and recognize when bounded integer keys, several sort keys or evenly spread values call for them.
Counting sort: keys as addresses
Every sort so far learned about the keys only by comparing two of them. If the keys are integers in a small range , there is a faster channel: use a key as an array index. Counting sort counts how many records have each key, turns the counts into running totals, which say where each key's block of the output begins, and then drops every record straight into its slot.
The version below sorts records by a key function and is stable: records with equal keys come out in their input order. That property is what the next step builds on.
def counting_sort(records, key, k):
"""Stable sort of records by key(r), an integer in 0..k-1. O(n + k) time and space."""
count = [0] * (k + 1)
for r in records:
count[key(r) + 1] += 1 # count[v + 1] = number of records with key v
for v in range(k):
count[v + 1] += count[v] # now count[v] = number of records with key < v
out = [None] * len(records)
for r in records: # left to right, so equal keys keep their order
out[count[key(r)]] = r
count[key(r)] += 1
return outTested against Python's sorted on thousands of random record lists, stability included. CLRS places the records from the right end with decreasing counts instead, which is equally stable; the widget below does it that way.
Running totals give positions. After the second loop,
count[v]is the number of records whose key is smaller than , which is exactly the first output index of key 's block:Stable placement. The third loop visits records in input order and fills each key's block from its left end, so the records with key land in in the order they arrived. Blocks appear in key order, so the output is sorted and stable.
Cost. Two passes over the records and one over the counters, with no comparison between keys at all:
Radix sort: one digit at a time
Radix sort writes each key with digits in base and sorts stably by the least significant digit first, then by the next digit, and so on up to the most significant. It looks backward, yet it works, as long as every pass is stable. CLRS's example, seven 3-digit keys:
| Input | After the ones digit | After the tens digit | After the hundreds digit |
|---|---|---|---|
| 329 | 720 | 720 | 329 |
| 457 | 355 | 329 | 355 |
| 657 | 436 | 436 | 436 |
| 839 | 457 | 839 | 457 |
| 436 | 657 | 355 | 657 |
| 720 | 329 | 457 | 720 |
| 355 | 839 | 657 | 839 |
Claim. After pass (counting from 1), the keys are sorted by their last digits. For this is what the first pass does.
Step. Pass sorts by digit . Two keys with different end up in the order of , which is the most significant of their last digits. Two keys with equal keep their relative order, because the pass is stable, and by induction that order is the order of their last digits. Either way, they are ordered by their last digits.
Cost. passes of counting sort with cost . For keys of bits read as digits of bits, and :
def radix_sort(a, bits=32, r=8):
"""LSD radix sort of non-negative integers below 2**bits, r bits per pass."""
mask = (1 << r) - 1
for shift in range(0, bits, r):
count = [0] * ((1 << r) + 1)
for x in a:
count[((x >> shift) & mask) + 1] += 1
for v in range(1 << r):
count[v + 1] += count[v]
out = [0] * len(a)
for x in a: # stable: keys with equal digits keep their order
d = (x >> shift) & mask
out[count[d]] = x
count[d] += 1
a = out
return aCounting sort on one -bit digit per pass, tested with and against sorted. For a million 32-bit keys, the formula favors : two passes, about basic steps, against four passes and for . But counters no longer fit in the fastest cache, so tuned implementations often prefer 8-bit digits; measure on your machine.
In LSD radix sort, what goes wrong if the final pass, on the most significant digit, may reorder keys whose leading digits are equal?
- Nothing: the last pass decides the order anyway
- Keys with the same leading digit come out in arbitrary order, undoing the work of the earlier passes; for example, 25 and 21 may end up as 25, 21
- The sort becomes slower but stays correct
- Only negative numbers are affected
Show the answer
B. Keys with the same leading digit come out in arbitrary order, undoing the work of the earlier passes; for example, 25 and 21 may end up as 25, 21
The earlier passes leave keys with equal leading digits ordered by their lower digits, and only stability carries that order through the final pass. An unstable final pass sorts by the leading digit alone.
MSD radix sort and strings
LSD needs keys of equal length and always processes every digit. Most significant digit first (MSD) radix sort goes the other way: split the keys into buckets by their first character, then sort each bucket recursively by the next character. A bucket with one key, or keys that have run out of characters, is finished. That suits strings, whose lexicographic order is decided by the first position where they differ.
def msd_sort(strings, d=0):
"""Sort strings by their characters from position d on (MSD radix sort)."""
if len(strings) <= 1:
return strings
out = [s for s in strings if len(s) == d] # strings that end here come first
buckets = {}
for s in strings:
if len(s) > d:
buckets.setdefault(s[d], []).append(s)
for c in sorted(buckets): # at most one bucket per character
out += msd_sort(buckets[c], d + 1)
return outTested against sorted on random strings over a small alphabet. With a fixed alphabet of size , an array of buckets replaces the sorted dictionary keys, and the cost is the total length of the distinguishing prefixes plus per call, which is why practical versions hand small buckets to insertion sort.
MSD radix sort reads only as many characters as it needs to tell the strings apart: on random strings that is about characters per string, however long the strings are. Two engineered variants matter in practice. American flag sort (McIlroy, Bostic & McIlroy, 1993) permutes the keys into their buckets in place instead of copying them. Three-way radix quicksort (Bentley & Sedgewick, 1997) partitions on the current character into smaller, equal and larger, and moves to the next character only inside the equal part, which handles long common prefixes and large alphabets gracefully.
Radix sorting also runs inside other algorithms: building a suffix array by prefix doubling radix-sorts pairs of ranks in every round, as the lesson Building Suffix Arrays: Doubling to SA-IS shows.
Bucket sort: when keys are spread evenly
Bucket sort trades a guarantee on the input for speed. For real keys in , make buckets, bucket holding the interval ; put every key in its bucket, sort each bucket, and concatenate. If the keys are independent and uniformly distributed, each bucket holds one key on average, and the small sorts cost almost nothing.
def bucket_sort(xs):
"""Sort floats in [0, 1): expected O(n) time when they are uniformly distributed."""
n = len(xs)
buckets = [[] for _ in range(n)]
for x in xs:
buckets[int(x * n)].append(x) # bucket i holds [i/n, (i+1)/n)
out = []
for b in buckets:
b.sort() # tiny on average; CLRS uses insertion sort
out += b
return outTested against sorted on random inputs. For keys in another range , rescale them to first.
Bucket sizes. Bucket receives keys, a binomial random variable with trials and success probability . With insertion sort inside the buckets, the cost is .
Second moment. :
Sum. By linearity of expectation, the total is linear (a simulation with averaged 1,997 against the predicted 1,999):
Why this beats n log n, and recognizing it
The bound counts the leaves of a decision tree whose every branch is a comparison of two keys. Counting sort branches on the value of a key, by using it as an address, and on the word RAM reading a -bit word and indexing an array cost each. So there is no contradiction, only a different model. The price is a dependence on the keys: on for counting sort, on the key length for radix sort, on the distribution for bucket sort.
Signals that one of these sorts fits:
- Bounded integer keys: ages, scores, years, values below when is about as large.
- Fixed-width keys and large : 32- or 64-bit integers, IP addresses, fixed-length codes, where a few counting passes beat comparisons.
- Several sort keys: stable passes from the least important key to the most important, exactly the LSD idea.
- Evenly spread reals, or a question about gaps between values that buckets can answer without full sorting.
| Problem, in brief | Key idea | Cost |
|---|---|---|
| Sort integers known to lie in | counting sort with counters | |
| Sort events by day, and by time within each day | stable sort by time, then stable sort by day (or one sort on the pair) | two linear passes for bounded keys |
| Sort 32-bit integers as fast as possible | LSD radix sort, 4 passes of 8 bits or 2 of 16 | per pass |
| The largest gap between neighbors in sorted order | buckets of width ; the gap never lies inside a bucket | |
| Suffix array by prefix doubling | radix-sort the pairs of ranks in every round | in all |
def max_gap(a):
"""Largest difference between neighbors in sorted order of integers, in O(n) time."""
n = len(a)
if n < 2 or min(a) == max(a):
return 0
lo, hi = min(a), max(a)
bmin, bmax = [None] * n, [None] * n # bucket i: (x - lo)(n - 1) // (hi - lo) == i
for x in a:
i = (x - lo) * (n - 1) // (hi - lo)
bmin[i] = x if bmin[i] is None else min(bmin[i], x)
bmax[i] = x if bmax[i] is None else max(bmax[i], x)
best, prev = 0, lo # two keys in one bucket differ by less than
for i in range(n): # (hi - lo)/(n - 1) <= the maximum gap, so the
if bmin[i] is not None: # answer always spans consecutive nonempty buckets
best = max(best, bmin[i] - prev)
prev = bmax[i]
return bestInteger arithmetic for the bucket index avoids floating-point rounding at bucket boundaries. Checked against sorting on thousands of random inputs. In the algebraic decision tree model this problem needs ; the floor in the bucket index is what escapes it.
Common bugs.
- Breaking stability: placing records right to left while the counts point at block starts, or left to right while they point at block ends. Radix sort then silently returns wrong answers.
- Negative integers: subtract the minimum first, or flip the sign bit so that two's-complement numbers sort as unsigned ones.
- Floating-point keys: IEEE 754 bit patterns sort correctly as unsigned integers after flipping all bits of negative numbers and only the sign bit of the others.
- Stale counts: forgetting to reset the counters between passes, or allocating counters where the shifted version needs .
- Huge ranges: allocating counters for a range far larger than .
You must sort integers from the range as fast as possible. Which approach fits?
- Counting sort with counters
- Bucket sort with 10 buckets
- Insertion sort, since the values are integers
- LSD radix sort on 10- or 15-bit digits: 3 or 2 counting passes, since
Show the answer
D. LSD radix sort on 10- or 15-bit digits: 3 or 2 counting passes, since
Each pass costs : about steps for 15-bit digits, so two passes do the job, with no comparisons. Counting sort on the whole key would spend most of its time and memory on a billion counters.
Key takeaways
- Counting sort sorts integers in stably in time and space: running totals of the counts give each key's block in the output.
- LSD radix sort makes stable passes, in base , or for -bit keys and -bit digits; it is correct only because every pass is stable.
- MSD radix sort reads only the distinguishing prefixes and suits strings; bucket sort runs in expected time on uniformly spread keys and degrades to on skewed ones.
- These sorts escape by using keys as indices, outside the comparison model; reach for them when keys are bounded integers, fixed-width digits or evenly spread values.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
You must sort 1,000 records whose keys are arbitrary 32-bit unsigned integers. Is counting sort on the whole key a good choice?
- Yes: it is linear time
- No: , so the time and space are dominated by about 4 billion counters; use a comparison sort, or radix sort on 8- or 16-bit digits
- Yes, if the records are first sorted by a comparison sort
- No: counting sort cannot handle numbers larger than
Show the answer
B. No: , so the time and space are dominated by about 4 billion counters; use a comparison sort, or radix sort on 8- or 16-bit digits
Counting sort's cost is , so it is linear only when the key range is . Here dwarfs . Radix sort applies counting sort to small digits instead, keeping at 256 or 65,536 per pass.
LSD radix sort sorts keys of 64 bits with 16-bit digits. How many passes does it make, and roughly how many basic steps?
- 20 passes, one per bit of , about steps
- 64 passes, one per bit, about steps
- 4 passes, about steps
- 1 pass over counters
Show the answer
C. 4 passes, about steps
digits, and each pass is a counting sort costing : in all about steps, linear in for fixed-width keys.
Bucket sort with buckets and insertion sort inside each bucket receives keys that all lie in . What is its running time?
Show the answer
C.
All keys land in bucket 0, and insertion sort on that bucket takes in the worst case. Bucket sort's is an expected bound for uniformly distributed keys, an average-case guarantee that depends on the input distribution.
Why does LSD radix sort, which sorts 32-bit keys in time, not contradict the sorting lower bound?
- The lower bound is only about the average case
- Radix sort reads digits of the keys and uses them as array indices, which the comparison model does not allow; the lower bound covers only comparison sorts
- Radix sort is actually because of its passes
- The lower bound assumes the keys are distinct
Show the answer
B. Radix sort reads digits of the keys and uses them as array indices, which the comparison model does not allow; the lower bound covers only comparison sorts
The decision-tree argument assumes the algorithm learns about the keys only from comparisons. Radix sort branches on key bits through array indexing on the word RAM, so the argument does not apply. With -bit keys it makes passes, a constant for fixed .
Go deeper
- Integer Sorting on the Word RAM · How fast can n integers be sorted? Fusion trees, signature sort and an open question.
- Sorting Networks & Parallel Sorting · The 0–1 principle, bitonic sort and the AKS network.
- External Sorting · Sorting data that does not fit in memory: runs, multiway merges and the I/O bound.
Further reading
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), sections 8.2–8.4.
- R. Sedgewick & K. Wayne, Algorithms, 4th ed. (Addison-Wesley, 2011), section 5.1, "String Sorts".
- P. M. McIlroy, K. Bostic & M. D. McIlroy, "Engineering radix sort," Computing Systems 6(1) (1993), 5–27.
- J. L. Bentley & R. Sedgewick, "Fast algorithms for sorting and searching strings," Proceedings of the 8th ACM-SIAM Symposium on Discrete Algorithms (1997).