Counting Sort
All the sorts so far work by comparing values. Counting sort never compares two values with each other. Instead it counts how many times each value occurs and then writes the values back in order. When the values are small non-negative integers (ages, grades from 0 to 10, dice rolls), this is faster than any comparison sort.
How it works
- Find the largest value
maxand create acountsarray ofmax + 1zeros. - For each value
vin the input, add one tocounts[v]. - Walk through
countsfrom index 0 upwards and write each indexvinto the arraycounts[v]times.
Implementation
def counting_sort(arr):
if not arr:
return arr
counts = [0] * (max(arr) + 1)
for v in arr:
counts[v] += 1
print("counts:", counts)
k = 0
for v, c in enumerate(counts):
for _ in range(c):
arr[k] = v
k += 1
return arr
print(counting_sort([4, 2, 2, 8, 3, 3, 1]))counts: [0, 1, 2, 2, 1, 0, 0, 0, 1]
[1, 2, 2, 3, 3, 4, 8]
The printed counts list is the same as the one in the animation's last frame: index 2 holds 2 because the value 2 occurs twice, index 8 holds 1, and so on.
The stable version: sorting records
The simple version recreates the values from their counts, which only works when the values are the whole data. To sort records by an integer key (people by age, orders by priority) we need a stable version. It turns the counts into starting positions with a running sum (a prefix sum), then places each record at its key's next free position:
def counting_sort_by(records, key, max_key):
counts = [0] * (max_key + 1)
for r in records:
counts[key(r)] += 1
# prefix sums: start[k] = how many records have a smaller key
start = [0] * (max_key + 1)
for k in range(1, max_key + 1):
start[k] = start[k - 1] + counts[k - 1]
print("counts:", counts)
print("start: ", start)
output = [None] * len(records)
for r in records: # left to right keeps equal keys in order
output[start[key(r)]] = r
start[key(r)] += 1
return output
tasks = [("deploy", 2), ("email", 0), ("backup", 2), ("review", 1), ("lunch", 0)]
for name, priority in counting_sort_by(tasks, key=lambda t: t[1], max_key=2):
print(priority, name)counts: [2, 1, 2]
start: [0, 2, 3]
0 email
0 lunch
1 review
2 deploy
2 backup
Records with the same priority keep their input order ("email" before "lunch", "deploy" before "backup"). This stable version is the building block of radix sort, next lesson.
The cost depends on the range
Counting sort takes O(n + k) time and O(k) extra memory, where n is the number of values and k is the range of values (max + 1). That is excellent when k is small compared with n, and terrible when it is not:
def counting_sort_work(arr):
k = max(arr) + 1
return len(arr) + k # one step per value plus one per counter
grades = [7, 9, 4, 10, 7, 8, 6, 9, 7, 5] * 100 # 1000 grades from 0 to 10
print("1000 grades in 0..10: ", counting_sort_work(grades), "steps")
salaries = [31000, 54000, 47000, 120000]
print("4 salaries up to 120000:", counting_sort_work(salaries), "steps")1000 grades in 0..10: 1011 steps
4 salaries up to 120000: 120005 steps
Four salaries need over 120,000 counters. A comparison sort would need only a handful of comparisons.
Limitations
| Requirement | Why |
|---|---|
| Integer keys | the value is used as an index into counts |
| Non-negative (or shift them) | for keys from lo to hi, use counts[v - lo] |
Small range k |
memory and time grow with k, not just n |
Properties
| Property | Counting sort |
|---|---|
| Time | O(n + k) |
| Extra memory | O(k) (plus O(n) for the stable version's output) |
| Stable? | The prefix-sum version is |
| Comparisons | none |
Note: Comparison sorts can be proven to need about
n log₂ ncomparisons in the worst case. Counting sort escapes that limit because it uses the values as array indexes instead of comparing them.
Test yourself
What does counts[5] hold after the counting step?
- The fifth value of the input
- How many times the value 5 occurs
- The index where 5 should go
- Always 0 or 1
When is counting sort a poor choice?
- When there are many values
- When values are integers 0–100
- When the range of values is huge compared with how many values there are
- When the data contains duplicates
What is the time complexity of counting sort with n values in the range 0..k-1?
- O(n log n)
- O(n²)
- O(n + k)
- O(k log n)