Counting Sort and Stability
The bound of Decision Trees and the Comparison Lower Bound holds for algorithms that only compare keys. If the keys are small integers, an algorithm can do something a comparison sort may not: use a key as an array index. Counting sort does exactly that. It sorts integers in the range to in time, which is linear whenever . It is also stable, and that property, more than its speed, is why it matters: it is the building block of radix sort.
The Counting Sort lesson in the DSA course shows the idea on bare numbers. This lesson does the version that sorts records, proves it stable, and analyses it.
The simple version: count, then write
For bare integers, counting is enough: count how many times each value occurs, then write each value that many times.
def counting_sort_values(a):
counts = [0] * (max(a) + 1)
for v in a:
counts[v] += 1
out = []
for v, c in enumerate(counts):
out += [v] * c
print("counts:", counts)
return out
print(counting_sort_values([3, 1, 4, 1, 5, 0, 3, 2]))counts: [1, 2, 1, 2, 1, 1]
[0, 1, 1, 2, 3, 3, 4, 5]
This works for numbers, but it throws the input elements away and recreates them from their keys. If each key carries satellite data (a name, an order number), the recreated "3" doesn't know which record it was. Sorting records needs a version that moves the records themselves.
The record version: prefix sums give positions
The trick is to turn the counts into positions. After counting, replace each count by a running total: becomes the number of keys . Then the records with key belong in the output positions to , a block whose size is the count of . Walk through the input and drop each record into the next free slot of its block.
COUNTING-SORT(a, k) // a[0..n-1] has integer keys 0..k; returns a new array
1 c = array of k + 1 zeros
2 for each x in a: c[key(x)] = c[key(x)] + 1 // c[v] = number of keys equal to v
3 for v = 1 to k: c[v] = c[v] + c[v - 1] // c[v] = number of keys <= v
4 b = array of length n
5 for i = n - 1 down to 0 // right to left: keeps it stable
6 c[key(a[i])] = c[key(a[i])] - 1
7 b[c[key(a[i])]] = a[i]
8 return bLine 5 walks backwards: the last record with key takes the last slot of 's block, the second-to-last takes the slot before it, and so on. Records with equal keys therefore keep their input order. (Walking forwards works too, if the running totals are shifted to give each block's first slot; the practice problem below can be solved either way.)
def counting_sort(records, k, key, trace=False):
c = [0] * (k + 1)
for x in records:
c[key(x)] += 1
if trace: print("counts: ", c)
for v in range(1, k + 1):
c[v] += c[v - 1]
if trace: print("running sums:", c)
out = [None] * len(records)
for i in range(len(records) - 1, -1, -1):
v = key(records[i])
c[v] -= 1
out[c[v]] = records[i]
if trace: print(f" place {records[i]} at position {c[v]}")
return out
orders = [(3, "ana"), (1, "bo"), (4, "cy"), (1, "di"), (5, "ed"), (0, "fay"), (3, "gus"), (2, "hal")]
result = counting_sort(orders, 5, key=lambda r: r[0], trace=True)
print(result)counts: [1, 2, 1, 2, 1, 1]
running sums: [1, 3, 4, 6, 7, 8]
place (2, 'hal') at position 3
place (3, 'gus') at position 5
place (0, 'fay') at position 0
place (5, 'ed') at position 7
place (1, 'di') at position 2
place (4, 'cy') at position 6
place (1, 'bo') at position 1
place (3, 'ana') at position 4
[(0, 'fay'), (1, 'bo'), (1, 'di'), (2, 'hal'), (3, 'ana'), (3, 'gus'), (4, 'cy'), (5, 'ed')]
The two records with key 1 come out as bo then di, and the two with key 3 as ana then gus: the input order. The practice problem Stable Counting Sort asks for exactly this, returning the sorted order of positions.
In C++
The same algorithm, sorting (key, name) records stably in two passes over the input plus one over the counts:
#include <cstdio>
#include <string>
#include <vector>
struct Record { int key; std::string name; };
std::vector<Record> counting_sort(const std::vector<Record>& a, int k) {
std::vector<int> c(k + 1, 0);
for (const Record& r : a) ++c[r.key];
for (int v = 1; v <= k; ++v) c[v] += c[v - 1];
std::vector<Record> out(a.size());
for (int i = static_cast<int>(a.size()) - 1; i >= 0; --i) out[--c[a[i].key]] = a[i];
return out;
}
int main() {
std::vector<Record> orders = {{3, "ana"}, {1, "bo"}, {4, "cy"}, {1, "di"},
{5, "ed"}, {0, "fay"}, {3, "gus"}, {2, "hal"}};
for (const Record& r : counting_sort(orders, 5)) std::printf("%d %s\n", r.key, r.name.c_str());
}0 fay
1 bo
1 di
2 hal
3 ana
3 gus
4 cy
5 ed
Correctness and stability
After line 3, is the number of keys at most , so the records with key must occupy exactly positions of a sorted output (with read as 0). The loop of lines 5 to 7 fills each block from its right end.
Invariant. At the start of the iteration for , for every key value : equals the start of 's block plus the number of records with key in , and the records with key in occupy the positions from to the end of the block, in their input order.
- Initialization. With no record has been placed, and is the end of 's block, which is its start plus the number of records with key in the whole array.
- Maintenance. The record with key goes to position , just left of the records with key placed so far, all of which come later in the input. Decreasing keeps the count right.
- Termination. At every record is placed in its key's block, and within each block the records are in input order. That is a stable sorted output.
Stability is not an accident of this particular implementation; it is the reason for walking backwards. A forward walk with the end-of-block counters would reverse every group of equal keys, which still sorts correctly but is anti-stable, and would break radix sort.
Cost
Lines 2 and 5 to 7 each make one pass over the records; lines 1 and 3 one pass over the counters. So counting sort runs in time and uses extra memory: the output array and the counters. It is not in place.
- If , the time is , beating every comparison sort.
- If is much larger than , the counter array dominates: sorting 1,000 numbers up to would need a billion counters. Radix sort, next lesson, solves that by applying counting sort to one digit at a time.
The program confirms the linear behaviour by counting the elementary steps of the four loops for growing with , and checks the result against Python's stable sort on random data with many duplicates.
import random
def counting_sort_steps(keys, k):
steps = 0
c = [0] * (k + 1); steps += k + 1
for v in keys:
c[v] += 1; steps += 1
for v in range(1, k + 1):
c[v] += c[v - 1]; steps += 1
out = [None] * len(keys)
for i in range(len(keys) - 1, -1, -1):
c[keys[i]] -= 1
out[c[keys[i]]] = (keys[i], i); steps += 1
return out, steps
rng = random.Random(12)
for n in [1000, 2000, 4000, 8000]:
keys = [rng.randint(0, n) for _ in range(n)]
out, steps = counting_sort_steps(keys, n)
expected = sorted(((v, i) for i, v in enumerate(keys)), key=lambda t: t[0]) # stable
assert out == expected
print(f"n = k = {n}: {steps} steps = {steps / n:.2f} n")
keys = [rng.randint(0, 3) for _ in range(20)]
order = [i for _, i in counting_sort_steps(keys, 3)[0]]
print("keys: ", keys)
print("order:", order)n = k = 1000: 4001 steps = 4.00 n
n = k = 2000: 8001 steps = 4.00 n
n = k = 4000: 16001 steps = 4.00 n
n = k = 8000: 32001 steps = 4.00 n
keys: [1, 1, 2, 2, 1, 3, 2, 2, 2, 3, 2, 2, 1, 0, 2, 3, 2, 0, 0, 0]
order: [13, 17, 18, 19, 0, 1, 4, 12, 2, 3, 6, 7, 8, 10, 11, 14, 16, 5, 9, 15]
The step count is exactly : to clear the counters, to count, for the running sums and to place. With that is , and doubling doubles the work. The second part shows stability on a small example: equal keys appear in increasing order of their positions.
Test yourself
Why does COUNTING-SORT place the records in a loop that runs from down to ?
- It is faster than a forward loop
- Each key's slots are filled from the right end of its block, so walking backwards keeps equal keys in input order
- The counters would become negative otherwise
- To avoid comparing keys
What is the running time of counting sort on keys in the range to ?
After the running-sum loop, the counters are [1, 3, 4, 6] for keys 0 to 3. Which output positions hold the records with key 2?
- position 2 only
- position 3 only
- positions 3 and 4
- positions 4 and 5
Why doesn't counting sort contradict the lower bound?
- It is not a comparison sort: it uses keys as array indices
- The bound only applies to stable sorts
- It is only fast on sorted inputs
- It makes comparisons in disguise