Intermediate 8 min
Counting sort
Counting sort tracks how often each key occurs and then visits the keys in order.
How it works
First turn each value into an occurrence count. The sample counts show that key 3 needs to appear twice. In the second pass, walk the key range in order and write that many copies of each key. The cost grows with the number of items plus the key range.
Walk through an example
If values are in 0 through 3, count visits to each of those four slots. Print each key the number of times it appears to reproduce a sorted list.
What to watch for
This approach needs space for the full key range. A few numbers spread over a huge interval can make counting sort a poor fit.
Code example
def sort_small(values, max_key):
counts = [0] * (max_key + 1)
for value in values:
counts[value] += 1
return [key for key, count in enumerate(counts) for _ in range(count)]Check your understanding
What are the counts for 0, 1, 2, and 3?
See the example and explanation
- Worked example
- Given
[3, 1, 3, 0] with values from 0 to 3 - Answer
[1, 1, 0, 2]
There is one 0, one 1, no 2, and two 3s.