Sub topic 3
Counting Sort: Build a Histogram, Then Rebuild the Array
This chapter assumes you can read Python lists and loops, know Big-O notation, and have seen the idea from the previous chapter: when keys are integers in a known range 0..k, you can use a key directly as an array index instead of comparing it to other keys.
Counting sort in its simplest form does exactly that. It makes two passes. The first pass counts how many times each value appears. The second pass walks through the counts in order and writes each value out as many times as it was counted.
The working model
A histogram here is an array counts of length k + 1, where counts[v] holds the number of times the value v appears in the input. Building it takes one pass over the input. Each element costs one array increment and no comparisons.
The array index already carries the order, so the histogram is sorted information. Reading counts from index 0 up to index k visits the values in ascending order. To rebuild the output, you emit v exactly counts[v] times for each v.
The code
def counting_sort_simple(a, k):
"""Sort non-negative integers in the range 0..k."""
counts = [0] * (k + 1)
for x in a:
counts[x] += 1
out = []
for value, c in enumerate(counts):
out.extend([value] * c)
return out
print(counting_sort_simple([3, 1, 4, 1, 5, 2, 0], 5)) # [0, 1, 1, 2, 3, 4, 5]Here is the trace for the example input [3, 1, 4, 1, 5, 2, 0] with k = 5:
| Value v | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| counts[v] | 1 | 2 | 1 | 1 | 1 | 1 |
| Emitted | 0 | 1, 1 | 2 | 3 | 4 | 5 |
The first loop runs n times and the second visits all k + 1 slots, so the total work grows with both n and k. A later chapter covers that cost in detail.
The key limitation: values are recreated, not moved
The rebuild pass never touches the original elements. It writes the integer value again from scratch. For bare integers this makes no difference, because one 1 is the same as any other 1.
Real data usually consists of records sorted by a key, such as employees by department number or packets by priority. If you count only the keys, the histogram tells you there are two records with key 1, but it has thrown away which records they were. You cannot rebuild ("bo", 1) from the number 1 alone.
Common errors
- Wrong
k. If any value is greater thank, thencounts[x]raisesIndexError. If you pass akfar larger than the real maximum, the code still gives the right answer but wastes time and memory scanning empty slots. - Negative values. In Python,
counts[-1]quietly increments the last slot instead of failing, so negative inputs produce wrong output without any error. Validate inputs, or shift them as shown in a later chapter. - Off-by-one size. The range
0..kcontainsk + 1values, so the array must have lengthk + 1, notk. - Using it on floats or large ranges. Keys must be integers you can index with, and the range must be small enough that an array of
k + 1slots fits in memory.
Exercise
Run countingsortsimple([2, 0, 2, 7], 5) in your head. What happens, and what is the smallest valid k for this input?
Show answer
The value 7 is out of range for a counts array of length 6, so counts[7] += 1 raises IndexError. The smallest valid k is 7, which gives a counts array of length 8, and the output is [0, 2, 2, 7].
Exercise
Why can't the histogram version sort [("ana", 2), ("bo", 1)] by the number in each tuple, even if you count the numbers correctly?
Show answer
The rebuild pass writes key values rather than the original items. After counting, it knows there is one key 1 and one key 2, but it no longer knows which names went with them, so it cannot output the records.