Counting Sort, Radix Sort and Bucket Sort Explained
No sort that works by comparing items can beat Omega(n log n) comparisons in the worst case. Counting sort and radix sort do not compare items at all. They use the key's value as an index, and that lets them sort in time that grows linearly with n, as long as the keys are the right kind. This post shows both, plus bucket sort, with their exact conditions. Examples use Python 3.10 or later and only the standard library.
Why the lower bound does not apply
The Omega(n log n) bound comes from counting outcomes: a comparison answers one yes/no question, and telling apart all n! possible orders of n items needs about log2(n!) such answers (the argument is in sorting algorithms compared). An algorithm that reads a key such as 7 and writes the item straight into slot 7 is not asking yes/no questions; it is using the key as an address, the way an array index works. The lower bound simply does not cover it. The cost moves elsewhere: these algorithms only work for keys that can serve as indices, and they pay in time and memory for the size of the key range.
Counting sort: O(n + k)
Suppose every key is an integer from 0 to k - 1. Counting sort makes three passes:
- Count how many items have each key, in an array of k counters.
- Turn the counts into starting positions with a running total (prefix sums): key v's items will occupy the output slots from
start[v]onward. - Walk the input in its original order and drop each item into the next free slot for its key.
def counting_sort(items, key, k):
"""Stable sort of items whose key(item) is an integer in range(k)."""
count = [0] * k
for x in items: # 1. count each key: O(n)
count[key(x)] += 1
start, total = [0] * k, 0
for v in range(k): # 2. prefix sums: O(k)
start[v] = total # first output slot for key v
total += count[v]
out = [None] * len(items)
for x in items: # 3. place in input order: O(n)
out[start[key(x)]] = x
start[key(x)] += 1
return out
ages = [3, 1, 4, 1, 5, 2, 0, 4]
print(counting_sort(ages, key=lambda a: a, k=6))
people = [("Ravi", 2), ("Ana", 0), ("Lee", 2), ("Mo", 1), ("Ida", 0)]
print(counting_sort(people, key=lambda p: p[1], k=3))
[0, 1, 1, 2, 3, 4, 4, 5]
[('Ana', 0), ('Ida', 0), ('Mo', 1), ('Ravi', 2), ('Lee', 2)]
Steps 1 and 3 each take O(n); step 2 takes O(k). So counting sort runs in O(n + k) time and uses O(n + k) extra space (the counts and the output). Because step 3 walks the input in order, items with equal keys come out in their input order, which makes this version stable: Ravi stays ahead of Lee, and Ana ahead of Ida. If you are sorting bare integers you can skip the placement step and just write each value count[v] times, but the stable version is the one that sorts records and the one radix sort needs.
O(n + k) is linear in n only when k is not much larger than n. Sorting a million exam scores from 0 to 100 is ideal. Sorting two numbers that happen to be far apart is not:
keys = [3, 999_999]
k = max(keys) + 1
print(f"{len(keys)} keys need a count array of {k:,} slots")
2 keys need a count array of 1,000,000 slots
Radix sort: O(d(n + k))
Radix sort handles large keys by sorting one digit at a time, so the counting array only ever needs one slot per possible digit. LSD (least significant digit first) radix sort sorts by the ones digit, then by the tens digit, then by the hundreds digit, and so on, using a stable counting sort for each pass:
def counting_sort_by_digit(nums, exp, base):
count = [0] * base
for x in nums:
count[(x // exp) % base] += 1
for d in range(1, base): # running totals: end position of each digit
count[d] += count[d - 1]
out = [0] * len(nums)
for x in reversed(nums): # walk backward so equal digits stay in order
d = (x // exp) % base
count[d] -= 1
out[count[d]] = x
return out
def radix_sort(nums, base=10):
"""LSD radix sort for non-negative integers."""
if not nums:
return []
exp = 1
while max(nums) // exp > 0: # one pass per digit of the largest number
nums = counting_sort_by_digit(nums, exp, base)
print(f"after digit {exp:>3}:", nums)
exp *= base
return nums
data = [170, 45, 75, 90, 802, 24, 2, 66]
result = radix_sort(data)
print(result == sorted(data))
after digit 1: [170, 90, 802, 2, 24, 45, 75, 66]
after digit 10: [802, 2, 24, 45, 66, 170, 75, 90]
after digit 100: [2, 24, 45, 66, 75, 90, 170, 802]
True
Why does sorting by the last digit first work? After the pass on digit i, the numbers are sorted by their last i digits. The next pass sorts by digit i + 1, and because that pass is stable, numbers with the same digit i + 1 keep the order the earlier passes gave them, that is, sorted by their last i digits. After the final pass they are sorted by every digit. Look at 802 and 2 after the tens pass: both have tens digit 0, and they stay in the order the ones pass left them. Stability is not optional here; with an unstable inner sort the earlier passes would be scrambled.
With d digits in base k, each pass is a counting sort costing O(n + k), so radix sort takes O(d(n + k)) time and O(n + k) extra space. The number of digits depends on the largest key: in base 10, numbers below 1,000 have at most 3 digits. When d and k are small constants, as with unsigned 32-bit integers sorted one byte at a time (d = 4, k = 256), the time is O(n). The base is a trade-off: a larger base means fewer passes but a larger counting array per pass.
This version handles non-negative integers only. Negative numbers need an offset or a separate pass for the sign. Strings can be radix sorted character by character, but strings of different lengths need care (pad them, or use the most-significant-digit-first variant). Floating-point numbers can be radix sorted only after converting their bit patterns into an order-preserving integer form, which is easy to get wrong.
Bucket sort, briefly
Bucket sort targets a different case: real numbers spread evenly over a known range, say [0, 1). Make n buckets, each covering an equal slice of the range, drop each value into its bucket, sort each bucket (here with insertion sort), and concatenate. If the input is uniformly distributed, each bucket holds about one item on average and the whole sort takes O(n) on average. If the input is not, many values can land in one bucket, and with insertion sort inside that bucket the worst case is O(n^2):
import random
def insertion_sort(a):
for i in range(1, len(a)):
x, j = a[i], i - 1
while j >= 0 and a[j] > x:
a[j + 1] = a[j]
j -= 1
a[j + 1] = x
def bucket_sort(values):
"""For floats in [0, 1): n buckets, each sorted with insertion sort."""
n = len(values)
buckets = [[] for _ in range(n)]
for v in values:
buckets[int(v * n)].append(v) # bucket i holds [i/n, (i+1)/n)
for b in buckets:
insertion_sort(b)
return [v for b in buckets for v in b], max(len(b) for b in buckets)
random.seed(5)
uniform = [random.random() for _ in range(1000)]
out, biggest = bucket_sort(uniform)
print(out == sorted(uniform), "largest bucket (uniform):", biggest)
clustered = [random.random() / 1000 for _ in range(1000)] # all in [0, 0.001)
out, biggest = bucket_sort(clustered)
print(out == sorted(clustered), "largest bucket (clustered):", biggest)
True largest bucket (uniform): 6
True largest bucket (clustered): 1000
With 1,000 uniform values the fullest bucket held 6; with 1,000 values squeezed into [0, 0.001), all of them landed in bucket 0, and the insertion sort in that bucket did all the work. The O(n) average is a statement about the input distribution, not a guarantee.
When they beat O(n log n), and when they do not
| Algorithm | Time | Extra space | Stable | Needs |
|---|---|---|---|---|
| Counting sort | O(n + k) | O(n + k) | Yes (prefix-sum version) | Integer keys in a range of size k |
| LSD radix sort | O(d(n + k)) | O(n + k) | Yes | Keys split into d digits in base k |
| Bucket sort | O(n) average, O(n^2) worst | O(n) | Yes, if each bucket's sort is stable | Roughly uniform values in a known range |
They are a good fit for many integers in a small range (ages, scores, bytes, ranks), fixed-width keys such as IDs or dates written as numbers, and as the inner step of other algorithms that need a linear-time stable sort. They are a bad idea when the key range is huge compared with n (the counting array costs time and memory for every possible key, used or not), when keys are floats, arbitrary strings or objects that you can only compare, and when n is small, where the counting array's setup costs more than the comparisons it saves.
Growth rates alone do not settle it. The Big O Complexity Analyzer puts n log2 n at 9,965.78 and n at 1,000 for n = 1000, but radix sort's linear term carries a factor of d passes, and each pass touches every item twice. In Python specifically, the built-in sorted() runs in compiled code while a hand-written counting sort runs as interpreted loops, so the built-in may well win at the sizes you have; measure with timeit on your own data before switching. The Algorithm Comparison Tool does not include these sorts; use it to see the comparison sorts they compete with, such as merge sort and quicksort at O(n log n).
Check yourself
- You need to sort a million integers between 0 and 999. What is the cost of counting sort? (O(n + k) with k = 1,000: about two passes over the million items plus a pass over 1,000 counters.)
- Why must the per-digit sort in LSD radix sort be stable? (So each pass keeps the order the earlier, less significant digits established.)
- How many passes does base-10 radix sort make on numbers up to 99,999? (5, one per digit.)