Count the range, then rebuild.
Exploit a small integer range while accounting for the range-sized memory cost.
01 The idea
Counting sort counts occurrences of each key, then reconstructs ordered values. It can run in O(n + k) time when n is the number of observations and k is the key range. That advantage depends on a suitably small range: a few widely spaced values can make the count array impractical. This version sorts nonnegative integers and reconstructs values rather than preserving attached record identities.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
def counting_sort(values):
if not values: return []
if any(type(value) is not int or value < 0 for value in values):
raise ValueError("Nonnegative integer keys required")
counts = [0] * (max(values) + 1)
for value in values: counts[value] += 1
return [value for value, count in enumerate(counts) for _ in range(count)]
print(counting_sort([3, 1, 2, 1, 0]))[0, 1, 1, 2, 3]
03 Under the hood
- 1
The key is used as an array index, which is why this implementation rejects negative and noninteger values.
- 2
The reconstruction repeats each key according to its count. Space includes the count array and the returned output list.
- 3
A stable counting sort for records uses cumulative positions and a separate placement pass. That form is useful as a component of radix sorting; do not confuse it with merely expanding a frequency table.
04 Your turn, builder
Use Counter to sort a few sparse integer keys without a range-sized array.
Reveal one possible solution +
from collections import Counter
values = [1000000, 2, 2]
counts = Counter(values)
result = [value for value in sorted(counts) for _ in range(counts[value])]
print(result)05 Check your signal
What does k represent in the O(n + k) bound?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.