Sub topic 7
Counting Sort Cost: O(n + k) and the Range Problem
This chapter assumes you already know the stable, prefix-sum version of counting sort from the previous chapter, counting_sort_by_key. It also assumes you can read Big-O notation and know that comparison sorts such as merge sort take O(n log n) time. Here we count exactly what counting sort spends, in time and in memory. Then we look at the one parameter that decides whether it is fast or unusable: the key range k.
Where the Work Goes
Counting sort makes four passes. Two of them walk the input, which has n items. The other two walk the count array, which has k + 1 slots, one for each possible key from 0 to k.
| Pass | What it does | Cost |
|---|---|---|
| Initialize counts | `counts = [0] * (k + 1)` | O(k) |
| Tally | Increment `counts[key(item)]` for each item | O(n) |
| Prefix sums | Turn counts into starting positions | O(k) |
| Place | Write each item to `out[counts[kv]]` | O(n) |
Adding the passes gives O(n) + O(k) + O(k) + O(n) = O(n + k). Neither term can be dropped in general. When n is huge and k is tiny, as with sorting a million exam scores in the range 0..100, the n passes dominate. When k is huge and n is tiny, the k passes dominate, even though most count slots stay at zero.
The algorithm has no best or worst case for a fixed n and k. Every pass runs the same number of steps whether the input is sorted, reversed, or random. Quicksort works differently: its running time depends on the order of the input.
An exact operation count
The following function counts the loop steps each pass performs for a given n and k. You can use it to see which term dominates.
import math
def counting_sort_steps(n, k):
"""Loop iterations performed by each pass of counting sort."""
return {
"init": k + 1,
"tally": n,
"prefix": k + 1,
"place": n,
"total": 2 * n + 2 * (k + 1),
}
def comparison_lower_bound(n):
"""Roughly the minimum comparisons any comparison sort needs: log2(n!)."""
return math.lgamma(n + 1) / math.log(2)
n = 10_000
for k in [1_000, 10_000, 100_000, 1_000_000]:
steps = counting_sort_steps(n, k)["total"]
print(f"k={k:>9,} counting steps={steps:>10,} "
f"comparison bound={comparison_lower_bound(n):>10,.0f}")With n = 10,000 the comparison bound is about 118,000 comparisons. Counting sort needs about 22,000 steps when k = 1,000 and about 40,000 when k = 10,000. At k = 100,000 it needs about 220,000 steps, and at k = 1,000,000 it needs about 2,000,000. Somewhere between k = 10,000 and k = 100,000 counting sort stops being the cheaper choice for this n.
Where the Memory Goes
Counting sort is not in place. The stable version allocates two arrays:
- The count array, with k + 1 entries.
- The output array, with n entries.
So the extra space is O(n + k). The output array is usually acceptable, since merge sort needs O(n) extra space too. The count array is the risky one, because its size depends on the values in the data rather than on how many values there are.
In CPython, a list stores an 8-byte pointer per slot. Small integers are cached objects, but counts larger than 256 become separate integer objects of about 28 bytes each. A conservative estimate is 8 bytes per count slot. In C or NumPy with 32-bit counters, it is 4 bytes per slot.
| Key type | k | Count array at 4 bytes/slot | Count array at 8 bytes/slot |
|---|---|---|---|
| Exam score | 100 | 404 B | 808 B |
| 16-bit integer | 65,535 | 256 KiB | 512 KiB |
| Days since 1900, up to 2100 | about 73,000 | about 285 KiB | about 570 KiB |
| 32-bit unsigned integer | 4,294,967,295 | 16 GiB | 32 GiB |
| 64-bit integer | about 1.8 × 10^19 | impossible | impossible |
This table is the range problem in short. Counting sort works well for 8-bit and 16-bit keys. It is impractical for arbitrary 32-bit keys and impossible for 64-bit keys, however small n is. Sorting ten 32-bit integers with plain counting sort would require a 16 GiB array that is almost entirely zeros.
Shrinking k with an Offset
The cost depends on the span of the keys, not on how large they are. If every key lies between lo and hi, subtract lo from each key. The count array then needs only hi - lo + 1 slots. The shift preserves order, so the result is still correct. A later chapter uses the same idea for negative numbers. Here it matters only for cost.
def counting_sort_by_key(items, key, k):
"""Stable sort of items whose key(item) is an integer in 0..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 counting_sort_offset(items, key):
"""Counting sort whose count array spans only min..max of the keys."""
if not items:
return []
keys = [key(item) for item in items]
lo, hi = min(keys), max(keys)
return counting_sort_by_key(items, lambda item: key(item) - lo, hi - lo)
orders = [("A17", 1_000_004), ("B02", 1_000_001), ("C33", 1_000_004), ("D90", 1_000_000)]
print(counting_sort_offset(orders, lambda o: o[1]))
# [('D90', 1000000), ('B02', 1000001), ('A17', 1000004), ('C33', 1000004)]Without the offset, those order IDs would need a count array of 1,000,005 slots. With it, they need 5.
One outlier ruins the offset
The offset helps only when the keys are clustered. Take a million keys in the range 0..999 plus a single key equal to 10^9. Now hi - lo is about 10^9, and the count array grows from 1,000 slots to a billion because of one value. This is the main failure mode in practice. Counting sort's cost depends on the data's extremes, which a single bad record can set. If your data can contain outliers, check hi - lo against n before you commit, and fall back to another algorithm when the span is too large.
When Is k "Small Enough"?
Big-O gives the first rule. Counting sort runs in linear time when k = O(n). If k grows no faster than a constant times n, then O(n + k) = O(n).
Constant factors and memory give the practical rules.
- Compare against n log n, not n. Counting sort beats a comparison sort roughly while k is below about n log2 n, divided by however much more each counting step costs than each comparison. The chart above shows this crossover.
- Watch the cache. The tally and place passes access
countsat random positions decided by the keys. A count array that fits in L1 or L2 cache (tens to hundreds of KiB) makes those accesses cheap. A count array of many megabytes turns almost every increment into a cache miss, and the algorithm can end up slower than its step count suggests. - Watch the zeros. The two k passes touch every slot, including empty ones. If k is 100 times n, about 99% of that work is spent on keys that never appear.
Measuring It Yourself
The script below fixes n and increases k, timing pure-Python counting sort against Python's built-in sorted.
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 identity(x):
return x
n = 100_000
for k in [10**2, 10**4, 10**5, 10**6, 10**7]:
data = [random.randint(0, k) for _ in range(n)]
t0 = time.perf_counter()
result = counting_sort_by_key(data, identity, k)
t1 = time.perf_counter()
expected = sorted(data)
t2 = time.perf_counter()
assert result == expected
print(f"k={k:>10,} counting={t1 - t0:6.3f}s sorted()={t2 - t1:6.3f}s")Two patterns appear. First, counting sort's time stays almost flat while k is at most n, then climbs roughly in proportion to k once k passes n. At k = 10^7 the two k passes do 100 times more work than the n passes. Second, sorted may beat the Python counting sort at every k. sorted is Timsort written in C, while each counting step here is an interpreted Python bytecode loop. Asymptotic comparisons only hold when both algorithms are implemented in the same way. In C, Rust, or NumPy, counting sort wins clearly for small k.
What to Do When k Is Too Large
When the range is too wide, you can try one of three approaches.
- Radix sort. Split each key into digits with a small range, such as 8 bits each so k = 255, and run one stable counting sort per digit. The next chapters build this. It is the standard fix for 32-bit and 64-bit keys.
- Count the distinct keys only. Tally keys in a dictionary, sort the u distinct keys with a comparison sort, then expand the counts. This costs O(n + u log u). It wins when there are many duplicates but the keys are spread out.
- Use a comparison sort. When keys are sparse, have few duplicates, and span a wide range, O(n log n) is the honest answer.
Exercise
You need to sort 50,000 records by a 16-bit sensor reading (0..65,535). Then you need to sort 50,000 records by a 32-bit timestamp whose values span 30 days measured in seconds. For each case, give k after the offset, the approximate count array size at 4 bytes per slot, and whether plain counting sort is a reasonable choice.
Show answer
Sensor readings: k is at most 65,535, so the count array takes about 256 KiB. That is comparable to n and fits in L2 cache on many CPUs, so counting sort is reasonable. Timestamps: after subtracting the minimum, k = 30 × 86,400 = 2,592,000, so the count array takes about 10 MiB. Since k is about 52 times n, the k passes dominate and the random accesses miss cache. Radix sort or a comparison sort is a better fit.
Exercise
A dataset has n = 1,000,000 keys. 999,999 of them lie in 0..999 and one equals 2,000,000,000. What is k with the min/max offset, and what does that do to counting sort's time and memory? Propose a cheap check that prevents this.
Show answer
lo = 0 and hi = 2,000,000,000, so k is about 2 × 10^9. The count array would need about 8 GB at 4 bytes per slot, and the two k passes would do about 2,000 times more work than the n passes. One cheap check is to compute hi - lo in the O(n) scan and use counting sort only if it stays below a threshold such as 4n or a fixed memory budget. Otherwise switch to radix sort or a comparison sort.
Exercise
Counting sort's running time does not change with input order, but quicksort's does. Explain why, using the four passes.
Show answer
Each pass runs a fixed number of iterations: k + 1 for initialization and for prefix sums, and n for tallying and for placement. No pass branches on how one key compares with another, so sorted, reversed, and random inputs all run the same 2n + 2(k + 1) loop steps. Quicksort's work depends on how the pivots split the data, and the splits depend on the input order.