Counting sort
Count how many times each key value occurs, then write the values back in order: O(n + k) time for small integer keys, with no comparisons at all.
Description
Comparison sorts can't beat O(n log n) in general: that's a proven lower bound. Counting sort sidesteps it by not comparing values. It only works when keys are small integers, from 0 to some maximum k.
It makes one pass to count how often each key appears, using an array of k + 1 counters. Then it walks the counters in order and writes each key out as many times as it was counted. Both passes are linear, so the sort is O(n + k).
To sort records by a key and keep it stable, the counts are turned into starting positions (a running total), and records are placed into an output array in their original order. That stable version is the building block of radix sort.
Counting sort is excellent when k is small compared with n: grades from 0–100, ages, ratings, bytes. When k is large, such as arbitrary 32-bit integers, the count array becomes too big.
How it works
Counts for [3, 1, 4, 1, 5, 2, 1]: no 0s, three 1s, and one each of 2, 3, 4 and 5
- count: 0, 3, 1, 1, 1, 1
Step through: counting sort writes each value back in order
Step 1 of 14Start with 12 values.
Complexity
| Operation | Average | Worst |
|---|---|---|
| Sort n keys in the range 0..k | O(n + k) | O(n + k) |
Space: O(n + k)
Counting sort is linear only while k stays proportional to n. Sorting a million numbers that range up to a billion would need a billion counters.
TypeScript implementation
A stable counting sort that sorts records by a small integer key.
// Stable counting sort: count keys, turn counts into start positions, then
// place each record in its original order.
export function countingSort<T>(items: T[], key: (item: T) => number, maxKey: number): T[] {
const count = new Array(maxKey + 2).fill(0);
for (const it of items) count[key(it) + 1]++;
for (let k = 0; k <= maxKey; k++) count[k + 1] += count[k]; // count[k] = first position for key k
const out = new Array<T>(items.length);
for (const it of items) out[count[key(it)]++] = it; // in original order: stable
return out;
}
export function demo(): string[] {
const reviews = [
{ id: "r1", stars: 4 }, { id: "r2", stars: 2 }, { id: "r3", stars: 5 },
{ id: "r4", stars: 4 }, { id: "r5", stars: 1 }, { id: "r6", stars: 2 },
];
const sorted = countingSort(reviews, (r) => r.stars, 5);
return [
`[${countingSort([3, 1, 4, 1, 5, 2, 1], (x) => x, 5).join(", ")}]`,
`reviews by stars (stable): ${sorted.map((r) => `${r.id}★${r.stars}`).join(", ")}`,
];
}When to use it
Use it when
- Keys are integers in a small range: ratings, ages, percentages, byte values.
- As the stable inner step of radix sort.
- Histograms, where you need the counts anyway.
Avoid it when
- The key range is large or unknown.
- Keys aren't integers or can't be mapped to small integers.
Pitfalls
- Huge count arrays when the maximum value is large.
- Negative keys: offset by the minimum first.
- Losing stability by writing records back from the counts instead of using prefix sums.
Alternatives
Radix sort
Choose it when keys are integers or fixed-length strings with a large range.
Built-in sort
Choose it when keys aren't small integers.