Counting Sort
Count how often each key occurs, turn the counts into positions, and write every value straight to its place. O(n + k) for integer keys below k.
SolvesSorting
- best
- O(n + k)
- average
- O(n + k)
- worst
- O(n + k)
- space
- O(n + k)
Counting sort never compares two values. It uses each key as an index into a table of counters. That lets it beat the limit of comparison sorts when the keys are integers in a small range .
A small key range: the largest key is 2, so there are only k = 3 counters. The time is n + k.
a (input)
counts (index = key)
result
1def counting_sort(a):2 k = max(a) + 13 counts = [0] * k4 for x in a:5 counts[x] = counts[x] + 16 # counts[v] becomes the number of keys <= v7 for v in range(1, k):8 counts[v] = counts[v] + counts[v - 1]9 result = [0] * len(a)10 # from the right: equal keys keep order11 for x in reversed(a):12 counts[x] = counts[x] - 113 result[counts[x]] = x14 return resultThe largest key is 2, so make 3 counters, all 0.
- counted
- 0
- prefixed
- 0
- placed
- 0
How it works
- Count.
counts[v]is the number of values equal tov. - Prefix sums. Add each counter to the next one. Now
counts[v]is the number of values . That is one past the last output index for keyv. - Place. Scan the input from right to left. For key
x, decreasecounts[x]and writextoresult[counts[x]].
Scanning from the right makes the sort stable: of two equal keys, the later one gets the later slot [1]. Stability matters when radix sort uses counting sort for each digit.
Complexity
| Case | Input | Time |
|---|---|---|
| Best | small key range | |
| Average | random keys below | |
| Worst | one huge key |
The order of the input does not matter. Only the key range does. Each loop runs or times. The counters and the result need memory.
Implementations
- Standard: counters, prefix sums and a right-to-left placement pass.
Pitfalls
- Keys must be integers from to . Negative keys need an offset by the minimum.
- With these decreasing counters, a left-to-right scan reverses the order of equal keys. The output is still sorted, but the sort is no longer stable.
- Memory is . It is not an in-place sort.
Related
References
- T. H. Cormen et al., Introduction to Algorithms, 3rd ed., MIT Press, 2009.
Further reading
- K. Mehlhorn and P. Sanders, Algorithms and Data Structures: The Basic Toolbox, Springer, 2008.