TExcelTAD
Home › Sorting & Order Statistics › Counting Sort and Stability

Counting Sort and Stability

The Ω(nlg⁡n)\Omega(n \lg n) 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 nn integers in the range 00 to kk in Θ(n+k)\Theta(n + k) time, which is linear whenever k=O(n)k = O(n). 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.

python · try it yourself
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: c[v]c[v] becomes the number of keys ≤v\le v. Then the records with key vv belong in the output positions c[v−1]c[v-1] to c[v]−1c[v] - 1, a block whose size is the count of vv. Walk through the input and drop each record into the next free slot of its block.

text
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 b

Line 5 walks backwards: the last record with key vv takes the last slot of vv'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.)

python · try it yourself
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:

cpp · try it yourself
#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, c[v]c[v] is the number of keys at most vv, so the records with key vv must occupy exactly positions c[v−1],…,c[v]−1c[v-1], \ldots, c[v] - 1 of a sorted output (with c[−1]c[-1] 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 ii, for every key value vv: c[v]c[v] equals the start of vv's block plus the number of records with key vv in a[0..i]a[0..i], and the records with key vv in a[i+1..n−1]a[i+1..n-1] occupy the positions from c[v]c[v] to the end of the block, in their input order.

  • Initialization. With i=n−1i = n - 1 no record has been placed, and c[v]c[v] is the end of vv's block, which is its start plus the number of records with key vv in the whole array.
  • Maintenance. The record a[i]a[i] with key vv goes to position c[v]−1c[v] - 1, just left of the records with key vv placed so far, all of which come later in the input. Decreasing c[v]c[v] keeps the count right.
  • Termination. At i=−1i = -1 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 nn records; lines 1 and 3 one pass over the k+1k + 1 counters. So counting sort runs in Θ(n+k)\Theta(n + k) time and uses Θ(n+k)\Theta(n + k) extra memory: the output array and the counters. It is not in place.

  • If k=O(n)k = O(n), the time is Θ(n)\Theta(n), beating every comparison sort.
  • If kk is much larger than nn, the counter array dominates: sorting 1,000 numbers up to 10910^9 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 nn with k=nk = n, and checks the result against Python's stable sort on random data with many duplicates.

python · try it yourself
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 2n+2k+12n + 2k + 1: k+1k + 1 to clear the counters, nn to count, kk for the running sums and nn to place. With k=nk = n that is 4n+14n + 1, and doubling nn 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 i=n−1i = n - 1 down to 00?

  1. It is faster than a forward loop
  2. Each key's slots are filled from the right end of its block, so walking backwards keeps equal keys in input order
  3. The counters would become negative otherwise
  4. To avoid comparing keys

What is the running time of counting sort on nn keys in the range 00 to kk?

  1. Θ(nlg⁡n)\Theta(n \lg n)
  2. Θ(n+k)\Theta(n + k)
  3. Θ(nk)\Theta(nk)
  4. Θ(klg⁡k)\Theta(k \lg k)

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?

  1. position 2 only
  2. position 3 only
  3. positions 3 and 4
  4. positions 4 and 5

Why doesn't counting sort contradict the Ω(nlg⁡n)\Omega(n \lg n) lower bound?

  1. It is not a comparison sort: it uses keys as array indices
  2. The bound only applies to stable sorts
  3. It is only fast on sorted inputs
  4. It makes nlg⁡nn \lg n comparisons in disguise