Counting sort
Counting sort counts how often each key appears, turns the counts into positions with prefix sums, and places items stably. No comparisons needed.
The idea
When values come from a small range, you can sort without comparing. Just tally how often each key appears.
Comparison sorts need at least n log n steps. Counting sort uses the keys as array indexes and skips comparisons.
Intuition
Add the tallies up. Each running total says how many values are at most that key.
The totals mark where each key's block ends. Key 2 owns slots 3 to 5 of the sorted output.
Three values are below key 2, so its block starts at slot 3. The running total 6 says where the block ends.
Complexity
Counting sort takes n + k steps for n values with keys from 0 to k. That beats n log n when k is small.
It reads the input twice, walks the count array once and writes the output once. No step depends on comparing two values.
It needs a count array of k + 1 cells and an output array of n cells. Extra space is n + k.
Pitfalls
Three values, the largest key 1,000, still need 1,001 count cells. A wide key range wastes time and memory.
Placing values left to right reverses equal keys. Going right to left keeps their input order.
A running total points at the end of a key's block. The last equal value belongs in the last slot, so scan backward.
Variations
Radix sort runs one stable counting sort per digit. The stability is what makes the later passes correct.
Negative keys shift by the minimum. With a minimum of -2, key -2 uses count cell 0.
Code
Pseudocode
countingSort(a, k)
count ← array of k + 1 zeros
for x in a
count[x] ← count[x] + 1
for v ← 1 to k
count[v] ← count[v] + count[v - 1]
output ← array of n slots
for i ← n - 1 down to 0
count[a[i]] ← count[a[i]] - 1
output[count[a[i]]] ← a[i]
return output
Python
def counting_sort(a, k):
count = [0] * (k + 1)
for x in a:
count[x] += 1
for v in range(1, k + 1):
count[v] += count[v - 1]
output = [0] * len(a)
for i in range(len(a) - 1, -1, -1):
count[a[i]] -= 1
output[count[a[i]]] = a[i]
return output
JavaScript
function countingSort(a, k) {
const count = new Array(k + 1).fill(0);
for (const x of a) {
count[x]++;
}
for (let v = 1; v <= k; v++) {
count[v] += count[v - 1];
}
const output = new Array(a.length);
for (let i = a.length - 1; i >= 0; i--) {
count[a[i]]--;
output[count[a[i]]] = a[i];
}
return output;
}
Java
static int[] countingSort(int[] a, int k) {
int[] count = new int[k + 1];
for (int x : a) {
count[x]++;
}
for (int v = 1; v <= k; v++) {
count[v] += count[v - 1];
}
int[] output = new int[a.length];
for (int i = a.length - 1; i >= 0; i--) {
count[a[i]]--;
output[count[a[i]]] = a[i];
}
return output;
}
Cost at a glance
| Best | O(n + k) |
|---|---|
| Average | O(n + k) |
| Worst | O(n + k) |
| Space | O(n + k) |
| Stable | yes |
| In-place | no |
| Adaptive | no |
Practice problems (7)
Fill the count array Warm-up
Follow counting sort on [3, 1, 3, 0, 2, 1, 3]. Before each count cell changes, type the number it will hold afterwards.
When counting sort fails Warm-up
For which input is counting sort a poor choice?
Count each key Warm-up
Given nums with every value between 0 and k, return an array count of length k + 1 where count[v] is how many times v appears in nums.
Implement counting sort Standard
Sort nums in ascending order with counting sort. Every value is an integer from 0 to k.
Count each key, turn the counts into running totals, then place the values from right to left into a new array. Return that array.
Fill in the stable placement Standard
Complete counting sort for integers from 0 to k. The running totals mark where each key block ends, and the values are placed from right to left.
Fill the three blanks.
Spot the bug: equal keys swap order Standard
This counting sort orders [key, id] pairs by key, but pairs with equal keys come out in reverse order. Click the line with the bug, then fix it.
Sort by a bounded key, stably Challenge
Each record is a string "grade:name", such as "90:eli", with a grade from 0 to 100. Return the records sorted by grade, ascending. Records with the same grade must keep their input order.
Use counting sort on the grade.
Next on the path: Trees: root, leaf, depth, height, subtree