Simple Algorithm
Algorithms & Data Structures · Optimized · 22 min

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 log⁡2(107!)≈2.2×108\log_2 (10^7!) \approx 2.2 \times 10^8 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 nlog⁡nn \log n "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 Θ(n+k)\Theta(n + k) time, and explain why its stability matters.
  • Implement LSD radix sort, prove it correct by induction on the digits, and choose the digit size: Θ((b/r)(n+2r))\Theta((b/r)(n + 2^r)) for bb-bit keys and rr-bit digits.
  • Use MSD radix sort for strings, and bucket sort for uniformly distributed reals in expected O(n)O(n) time.
  • Explain why these sorts escape the Ω(nlog⁡n)\Omega(n \log n) 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 0..k−10..k-1, 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.

python
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 out

Tested 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.

DerivationCorrectness and cost
  1. count[v]=#{ r:key(r)<v }\mathtt{count}[v] = \#\{\, r : \mathrm{key}(r) < v \,\}

    Running totals give positions. After the second loop, count[v] is the number of records whose key is smaller than vv, which is exactly the first output index of key vv's block:

  2. Stable placement. The third loop visits records in input order and fills each key's block from its left end, so the nvn_v records with key vv land in out[count[v]..count[v]+nv−1]\mathtt{out}[\mathtt{count}[v] .. \mathtt{count}[v] + n_v - 1] in the order they arrived. Blocks appear in key order, so the output is sorted and stable.

  3. T(n,k)=Θ(n+k) time,Θ(n+k) extra spaceT(n, k) = \Theta(n + k) \text{ time}, \qquad \Theta(n + k) \text{ extra space}

    Cost. Two passes over the nn records and one over the kk counters, with no comparison between keys at all:

Radix sort: one digit at a time

Radix sort writes each key with dd digits in base bb 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:

InputAfter the ones digitAfter the tens digitAfter the hundreds digit
329720720329
457355329355
657436436436
839457839457
436657355657
720329457720
355839657839
Each column is a stable counting sort of the previous one by a single digit. In the third pass, 436 and 457 share the hundreds digit 4, and they keep the order that the tens pass gave them.
DerivationWhy least significant digit first works
  1. after pass j: sorted by (xj−1,…,x1,x0)\text{after pass } j:\ \text{sorted by } (x_{j-1}, \dots, x_1, x_0)

    Claim. After pass jj (counting from 1), the keys are sorted by their last jj digits. For j=1j = 1 this is what the first pass does.

  2. Step. Pass j+1j + 1 sorts by digit xjx_j. Two keys with different xjx_j end up in the order of xjx_j, which is the most significant of their last j+1j + 1 digits. Two keys with equal xjx_j keep their relative order, because the pass is stable, and by induction that order is the order of their last jj digits. Either way, they are ordered by their last j+1j + 1 digits.

  3. T=Θ ⁣(wr (n+2r)),minimized near r≈log⁡2nT = \Theta\!\left(\frac{w}{r}\,\bigl(n + 2^r\bigr)\right), \quad \text{minimized near } r \approx \log_2 n

    Cost. dd passes of counting sort with k=bk = b cost Θ(d(n+b))\Theta(d(n + b)). For keys of ww bits read as digits of rr bits, d=⌈w/r⌉d = \lceil w/r \rceil and b=2rb = 2^r:

python
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 a

Counting sort on one rr-bit digit per pass, tested with r=8r = 8 and r=16r = 16 against sorted. For a million 32-bit keys, the formula favors r=16r = 16: two passes, about 2.1×1062.1 \times 10^6 basic steps, against four passes and 4.0×1064.0 \times 10^6 for r=8r = 8. But 2162^{16} counters no longer fit in the fastest cache, so tuned implementations often prefer 8-bit digits; measure on your machine.

Check your understanding

In LSD radix sort, what goes wrong if the final pass, on the most significant digit, may reorder keys whose leading digits are equal?

  1. Nothing: the last pass decides the order anyway
  2. 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
  3. The sort becomes slower but stays correct
  4. 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.

python
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 out

Tested against sorted on random strings over a small alphabet. With a fixed alphabet of size σ\sigma, an array of σ\sigma buckets replaces the sorted dictionary keys, and the cost is the total length of the distinguishing prefixes plus O(σ)O(\sigma) 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 log⁡σn\log_\sigma n 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 nn real keys in [0,1)[0, 1), make nn buckets, bucket ii holding the interval [i/n,(i+1)/n)[i/n, (i+1)/n); 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.

python
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 out

Tested against sorted on random inputs. For keys in another range [lo,hi)[lo, hi), rescale them to [0,1)[0, 1) first.

DerivationExpected linear time
  1. ni∼Binomial ⁣(n,1n),T=O(n+∑ini2)n_i \sim \mathrm{Binomial}\!\left(n, \tfrac1n\right), \qquad T = O\Big(n + \sum_{i} n_i^2\Big)

    Bucket sizes. Bucket ii receives nin_i keys, a binomial random variable with nn trials and success probability 1/n1/n. With insertion sort inside the buckets, the cost is O(n+∑ini2)O(n + \sum_i n_i^2).

  2. E[ni2]=n⋅1n(1−1n)+12=2−1n\E[n_i^2] = n \cdot \tfrac1n \left(1 - \tfrac1n\right) + 1^2 = 2 - \tfrac1n

    Second moment. E[ni2]=Var⁡[ni]+E[ni]2\E[n_i^2] = \operatorname{Var}[n_i] + \E[n_i]^2:

  3. E[∑ini2]=n(2−1n)=2n−1⟹E[T]=O(n)\E\Big[\sum_i n_i^2\Big] = n\left(2 - \tfrac1n\right) = 2n - 1 \quad\Longrightarrow\quad \E[T] = O(n)

    Sum. By linearity of expectation, the total is linear (a simulation with n=1000n = 1000 averaged 1,997 against the predicted 1,999):

Why this beats n log n, and recognizing it

The Ω(nlog⁡n)\Omega(n \log n) 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 ww-bit word and indexing an array cost O(1)O(1) each. So there is no contradiction, only a different model. The price is a dependence on the keys: on kk 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 10610^6 when nn is about as large.
  • Fixed-width keys and large nn: 32- or 64-bit integers, IP addresses, fixed-length codes, where a few counting passes beat nlog⁡nn \log n 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 briefKey ideaCost
Sort n≤107n \le 10^7 integers known to lie in 0..1060..10^6counting sort with 106+110^6 + 1 countersO(n+k)O(n + k)
Sort events by day, and by time within each daystable sort by time, then stable sort by day (or one sort on the pair)two linear passes for bounded keys
Sort 10710^7 32-bit integers as fast as possibleLSD radix sort, 4 passes of 8 bits or 2 of 16O(n)O(n) per pass
The largest gap between neighbors in sorted ordernn buckets of width (max⁡−min⁡)/(n−1)(\max - \min)/(n - 1); the gap never lies inside a bucketO(n)O(n)
Suffix array by prefix doublingradix-sort the pairs of ranks in every roundO(nlog⁡n)O(n \log n) in all
For the largest gap, nn values leave n−1n - 1 gaps summing to max⁡−min⁡\max - \min, so the largest gap is at least the bucket width, while two values in the same bucket are closer than that. Only the minimum and maximum of each bucket matter.
python
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 best

Integer 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 Ω(nlog⁡n)\Omega(n \log n); 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 kk counters where the shifted version needs k+1k + 1.
  • Huge ranges: allocating counters for a range far larger than nn.
Check your understanding

You must sort n=106n = 10^6 integers from the range [0,109)[0, 10^9) as fast as possible. Which approach fits?

  1. Counting sort with 10910^9 counters
  2. Bucket sort with 10 buckets
  3. Insertion sort, since the values are integers
  4. LSD radix sort on 10- or 15-bit digits: 3 or 2 counting passes, since 109<23010^9 < 2^{30}
Show the answer

D. LSD radix sort on 10- or 15-bit digits: 3 or 2 counting passes, since 109<23010^9 < 2^{30}

Each pass costs Θ(n+2r)\Theta(n + 2^r): about 106+21510^6 + 2^{15} 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 nn integers in 0..k−10..k-1 stably in Θ(n+k)\Theta(n + k) time and space: running totals of the counts give each key's block in the output.
  • LSD radix sort makes dd stable passes, Θ(d(n+b))\Theta(d(n + b)) in base bb, or Θ((w/r)(n+2r))\Theta((w/r)(n + 2^r)) for ww-bit keys and rr-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 O(n)O(n) time on uniformly spread keys and degrades to Θ(n2)\Theta(n^2) on skewed ones.
  • These sorts escape Ω(nlog⁡n)\Omega(n \log n) 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.

Question 1

You must sort 1,000 records whose keys are arbitrary 32-bit unsigned integers. Is counting sort on the whole key a good choice?

  1. Yes: it is linear time
  2. No: k=232k = 2^{32}, so the Θ(n+k)\Theta(n + k) time and space are dominated by about 4 billion counters; use a comparison sort, or radix sort on 8- or 16-bit digits
  3. Yes, if the records are first sorted by a comparison sort
  4. No: counting sort cannot handle numbers larger than nn
Show the answer

B. No: k=232k = 2^{32}, so the Θ(n+k)\Theta(n + k) 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 Θ(n+k)\Theta(n + k), so it is linear only when the key range kk is O(n)O(n). Here kk dwarfs nn. Radix sort applies counting sort to small digits instead, keeping kk at 256 or 65,536 per pass.

Question 2

LSD radix sort sorts n=220n = 2^{20} keys of 64 bits with 16-bit digits. How many passes does it make, and roughly how many basic steps?

  1. 20 passes, one per bit of log⁡2n\log_2 n, about 2×1072 \times 10^7 steps
  2. 64 passes, one per bit, about 6.7×1076.7 \times 10^7 steps
  3. 4 passes, about 4×(220+216)≈4.5×1064 \times (2^{20} + 2^{16}) \approx 4.5 \times 10^6 steps
  4. 1 pass over 2642^{64} counters
Show the answer

C. 4 passes, about 4×(220+216)≈4.5×1064 \times (2^{20} + 2^{16}) \approx 4.5 \times 10^6 steps

64/16=464 / 16 = 4 digits, and each pass is a counting sort costing Θ(n+216)\Theta(n + 2^{16}): in all about 4.5×1064.5 \times 10^6 steps, linear in nn for fixed-width keys.

Question 3

Bucket sort with nn buckets and insertion sort inside each bucket receives nn keys that all lie in [0,1/n)[0, 1/n). What is its running time?

  1. O(n)O(n)
  2. Θ(nlog⁡n)\Theta(n \log n)
  3. Θ(n2)\Theta(n^2)
  4. O(nlog⁡log⁡n)O(n \log \log n)
Show the answer

C. Θ(n2)\Theta(n^2)

All keys land in bucket 0, and insertion sort on that bucket takes Θ(n2)\Theta(n^2) in the worst case. Bucket sort's O(n)O(n) is an expected bound for uniformly distributed keys, an average-case guarantee that depends on the input distribution.

Question 4

Why does LSD radix sort, which sorts nn 32-bit keys in Θ(n)\Theta(n) time, not contradict the Ω(nlog⁡n)\Omega(n \log n) sorting lower bound?

  1. The lower bound is only about the average case
  2. 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
  3. Radix sort is actually Θ(nlog⁡n)\Theta(n \log n) because of its passes
  4. 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 ww-bit keys it makes w/rw/r passes, a constant for fixed ww.

Go deeper

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).