Sub topic 3
Counting Sort: Build a Histogram, Then Rebuild the Array
This chapter assumes you can read Python lists, loops, and functions, and that you know what O(n) means. The previous chapter showed that if keys are integers in a known range 0..k, you can use a key directly as an array index. This chapter turns that idea into the simplest working version of counting sort. You will trace it by hand, test its edge cases, and find the limitation that the next few chapters fix.
The Idea in Two Phases
Counting sort never compares two elements. Instead it asks one question about each element: "what is your value?" It then records the answer in a tally.
The algorithm has two phases:
- Count. Make an array
countsof lengthk + 1, filled with zeros. For each input valuex, add one tocounts[x]. When this phase ends,counts[v]holds the number of timesvappears in the input. This array is a histogram, which is a table of how often each value occurs. - Rebuild. Walk through
countsfrom index0to indexk. For each indexv, writevto the outputcounts[v]times.
The rebuild phase visits values in increasing order, so the output comes out sorted. Nothing gets compared. The order comes from the order of the array indices.
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]Each line in the count loop does constant work, and so does each entry in the rebuild loop, apart from the values it writes. Chapter 7 analyzes the cost in full. For now, note that the function makes one pass over the n inputs and one pass over the k + 1 counts.
Tracing the Count Phase
Here is the histogram after each input element is processed, for the input [3, 1, 4, 1, 5, 2, 0] with k = 5.
| Step | Element read | counts[0] | counts[1] | counts[2] | counts[3] | counts[4] | counts[5] |
|---|---|---|---|---|---|---|---|
| start | none | 0 | 0 | 0 | 0 | 0 | 0 |
| 1 | 3 | 0 | 0 | 0 | 1 | 0 | 0 |
| 2 | 1 | 0 | 1 | 0 | 1 | 0 | 0 |
| 3 | 4 | 0 | 1 | 0 | 1 | 1 | 0 |
| 4 | 1 | 0 | 2 | 0 | 1 | 1 | 0 |
| 5 | 5 | 0 | 2 | 0 | 1 | 1 | 1 |
| 6 | 2 | 0 | 2 | 1 | 1 | 1 | 1 |
| 7 | 0 | 1 | 2 | 1 | 1 | 1 | 1 |
The rebuild phase reads the last row from left to right. It emits one 0, two 1s, one 2, one 3, one 4, and one 5. The counts always add up to n. That gives you a quick sanity check: sum(counts) == len(a) must hold after the count phase.
An In-Place Variant
The version above allocates a new list. When the input is a bare list of integers, you can overwrite the input instead, because the histogram holds everything you need to rebuild it:
def counting_sort_inplace(a, k):
"""Sort a list of integers in 0..k in place, overwriting a."""
counts = [0] * (k + 1)
for x in a:
counts[x] += 1
i = 0
for value, c in enumerate(counts):
for _ in range(c):
a[i] = value
i += 1
data = [3, 1, 4, 1, 5, 2, 0]
counting_sort_inplace(data, 5)
print(data) # [0, 1, 1, 2, 3, 4, 5]This works because the program never needs the original elements back. It only needs their values, and the histogram has already stored those. The trick depends on that fact, and later in the chapter you will see why it breaks for records.
When You Don't Know k
The caller often doesn't know k ahead of time. You can compute the range from the data at the cost of one extra pass. Shifting by the minimum also lets the array start at the smallest value present instead of at zero. That saves space when values cluster far from zero, and it handles negative numbers:
def counting_sort_range(a):
"""Sort any list of integers by counting over the range min(a)..max(a)."""
if not a:
return []
lo, hi = min(a), max(a)
counts = [0] * (hi - lo + 1)
for x in a:
counts[x - lo] += 1
out = []
for i, c in enumerate(counts):
if c:
out.extend([i + lo] * c)
return out
print(counting_sort_range([1003, 1001, 1003, 1000])) # [1000, 1001, 1003, 1003]
print(counting_sort_range([4, -2, 0, -2, 7])) # [-2, -2, 0, 4, 7]
print(counting_sort_range([])) # []The array size is now hi - lo + 1, the spread of the data, and the magnitude of the values no longer matters. A list of values between 1,000,000 and 1,000,010 needs only 11 counters. A list containing just 0 and 10**9 still needs a billion counters, and no offset fixes that. Chapter 7 covers this range problem in detail.
Edge Cases and Common Errors
Most bugs in counting sort come from input that breaks the "integers in 0..k" contract. Python reports some of these violations loudly and lets others pass without any error.
| Input problem | What `counting_sort_simple` does | Severity |
|---|---|---|
| Empty list | Returns `[]` after scanning `k + 1` zero counts | Correct |
| Value greater than `k` | Raises `IndexError` | Loud, easy to find |
| Float such as `2.0` | Raises `TypeError` (list indices must be integers) | Loud |
| Negative value such as `-1` | Increments `counts[k]` through negative indexing and returns wrong output | Silent, dangerous |
| `k` much larger than needed | Correct, but wastes time and memory on empty counters | Performance only |
| `bool` values | Works, because `True == 1` and `False == 0` in Python | Surprising but correct |
A defensive version checks the contract before it touches the histogram:
def counting_sort_checked(a, k):
"""Like counting_sort_simple, but rejects values outside 0..k."""
counts = [0] * (k + 1)
for x in a:
if not isinstance(x, int) or not 0 <= x <= k:
raise ValueError(f"value {x!r} is not an integer in 0..{k}")
counts[x] += 1
out = []
for value, c in enumerate(counts):
out.extend([value] * c)
return out
print(counting_sort_checked([2, 0, 1], 2)) # [0, 1, 2]
try:
counting_sort_checked([2, -1, 0], 2)
except ValueError as e:
print(e) # value -1 is not an integer in 0..2What the Histogram Throws Away
Suppose you want to sort people by score, where each person is a tuple like ("ana", 2). Counting the scores is easy. The rebuild phase is where it breaks. The histogram says "two items had score 2", but it doesn't say which two. The names are gone.
people = [("ana", 2), ("bo", 1), ("cy", 2), ("di", 0)]
scores = [score for _, score in people]
print(counting_sort_simple(scores, 2)) # [0, 1, 2, 2] -- sorted scores, no namesFor bare integers this doesn't matter, because two copies of 2 are interchangeable. For records it ruins the result. The histogram version sorts keys, not data.
There is a quick fix: keep a list per key and append whole records to it.
def bucket_by_key(items, key, k):
buckets = [[] for _ in range(k + 1)]
for item in items:
buckets[key(item)].append(item)
return [item for b in buckets for item in b]
print(bucket_by_key(people, lambda p: p[1], 2))
# [('di', 0), ('bo', 1), ('ana', 2), ('cy', 2)]This works, but it allocates k + 1 separate lists that grow dynamically. That adds memory overhead and scatters records across the heap. The standard solution keeps the single integer count array and changes what the counts mean. Prefix sums turn counts into output positions, so each record can be copied directly into one flat output array. Before building that, you need a precise idea of what it means for equal keys like ana and cy to keep their relative order. That idea, stability, is the topic of the next chapter.
Exercises
Exercise
What does countingsortsimple([2, -1, 0], 2) return, and why?
Show answer
It returns [0, 2, 2]. The 2 increments counts[2]. The -1 increments counts[-1], which in Python is also counts[2], so counts[2] becomes 2. The 0 increments counts[0]. The final histogram is [1, 0, 2], which rebuilds as [0, 2, 2]. The output has the right length, but the -1 has been replaced by a 2 without any error.
Exercise
Modify countingsortsimple so it returns values in descending order without sorting the result afterward. What is the smallest change?
Show answer
Scan the histogram backward in the rebuild phase. Replace the rebuild loop with: for value in range(k, -1, -1): out.extend([value] * counts[value]). The count phase doesn't change.
Exercise
You need to sort 10 million bytes (values 0 to 255). Is the histogram version of counting sort appropriate, and how large is the count array?
Show answer
Yes. Bytes with the same value are indistinguishable, so no attached data is lost. The count array has only 256 entries, which is tiny compared with n. The sort makes one pass to count and one pass to write 10 million values.
Exercise
countingsortrange([0, 10**9]) is correct but slow and memory-hungry. Explain why, using the size of the count array.
Show answer
The count array has hi - lo + 1 = 10**9 + 1 entries, so the function allocates and scans about a billion counters to sort two numbers. Offsetting by the minimum shrinks the array only when the values sit close together. Here the spread itself is huge, so counting sort is the wrong tool.