/utils

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 Ω(nlog⁡n)\Omega(n \log n) limit of comparison sorts when the keys are integers in a small range 0…k−10 \dots k - 1.

A small key range: the largest key is 2, so there are only k = 3 counters. The time is n + k.

a (input)

2001122314052617

counts (index = key)

000102

result

0001020304050607
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 result
1 / 28

The largest key is 2, so make 3 counters, all 0.

counted
0
prefixed
0
placed
0

How it works

  1. Count. counts[v] is the number of values equal to v.
  2. Prefix sums. Add each counter to the next one. Now counts[v] is the number of values ≤v\le v. That is one past the last output index for key v.
  3. Place. Scan the input from right to left. For key x, decrease counts[x] and write x to result[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

CaseInputTime
Bestsmall key rangeO(n+k)O(n + k)
Averagerandom keys below kkO(n+k)O(n + k)
Worstone huge keyO(n+k)O(n + k)

The order of the input does not matter. Only the key range kk does. Each loop runs nn or k−1k - 1 times. The counters and the result need O(n+k)O(n + k) memory.

Implementations

  • Standard: counters, prefix sums and a right-to-left placement pass.

Pitfalls

  • Keys must be integers from 00 to k−1k - 1. 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 O(n+k)O(n + k). It is not an in-place sort.

Related

References

  1. 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.

Full bibliography