Sub topic 6
Stable Counting Sort for Records with Keys
This chapter assumes you have read the earlier chapters on the counting histogram, stability, and prefix sums. You should be comfortable with Python lists and lambdas. You should also be able to read an O(n + k) bound. The goal here is to combine those pieces into one function. It sorts records (tuples, objects, dictionaries) by an integer key, and it keeps records with equal keys in their original order.
Why the Histogram Version Is Not Enough
The histogram version of counting sort counts how many times each value appears. It then writes each value back that many times. That works for bare integers, because two copies of 3 are interchangeable. A record such as ("ana", 2) is different. Its key is 2, but the record also carries a name. If you only keep counts, the names are lost. You cannot rebuild ("ana", 2) from the fact that "key 2 appeared twice."
Records have to be moved, not regenerated. Prefix sums tell us where each key's block of output slots begins. Each record can then be copied straight into its final slot.
The Algorithm in Three Passes
The stable version makes three passes:
- Count. Tally how many records have each key, for keys
0..k. - Convert to positions. Replace the counts with exclusive prefix sums. After this pass,
counts[v]is the first output index for keyv. - Place. Walk the input from left to right. Put each record at
counts[key], then increment that entry so the next record with the same key goes one slot to the right.
The input is read twice: once to count and once to place. The second read is what moves the actual records.
The Implementation
def counting_sort_by_key(items, key, k):
"""Stable sort of items whose key(item) is an integer in 0..k."""
counts = [0] * (k + 1)
for item in items:
counts[key(item)] += 1
# Exclusive prefix sums: counts[v] becomes the first output index for key v.
total = 0
for v in range(k + 1):
counts[v], total = total, total + counts[v]
out = [None] * len(items)
for item in items: # forward pass keeps equal keys in input order
kv = key(item)
out[counts[kv]] = item
counts[kv] += 1
return out
people = [("ana", 2), ("bo", 1), ("cy", 2), ("di", 0)]
print(counting_sort_by_key(people, lambda p: p[1], 2))
# [('di', 0), ('bo', 1), ('ana', 2), ('cy', 2)]Some details are easy to get wrong:
- The
keyparameter works like thekeyargument of Python'ssorted. The function never looks at the rest of the record. It only moves the record. - The line
counts[v], total = total, total + counts[v]evaluates the right side before assigning.counts[v]therefore gets the running total before this key's count is added. That is what makes the prefix sum exclusive. - The same
countsarray is reused three times: as tallies, then as start indices, then as "next free slot" cursors. Using one array keeps the extra space at k + 1 integers.
Tracing the Example
With people and k = 2, the counting pass gives counts = [1, 1, 2]. The exclusive prefix sums give counts = [0, 1, 2]. Key 0 starts at index 0, key 1 at index 1, and key 2 at index 2.
The placement pass then runs as follows:
| Step | Record | Key | Slot written | `counts` after |
|---|---|---|---|---|
| 1 | `("ana", 2)` | 2 | `out[2]` | `[0, 1, 3]` |
| 2 | `("bo", 1)` | 1 | `out[1]` | `[0, 2, 3]` |
| 3 | `("cy", 2)` | 2 | `out[3]` | `[0, 2, 4]` |
| 4 | `("di", 0)` | 0 | `out[0]` | `[1, 2, 4]` |
ana and cy share key 2. ana comes first in the input, so it reaches counts[2] first and takes slot 2. cy then gets slot 3. When the pass ends, each counts[v] holds the first index of the next key's block, so every slot has been filled exactly once.
Why the Forward Pass Is Stable
Within one key's block, slots are handed out in increasing order: start, start + 1, start + 2, and so on. The forward pass visits records in input order. So the i-th record with key v in the input gets the i-th slot of v's block. Equal keys keep their relative order, which is the definition of stability.
Records with different keys never compete for slots. Their blocks do not overlap, because the prefix sums divide the output into disjoint ranges ordered by key. Being correct (keys in order) and being stable (ties in input order) come from two separate facts. The prefix sums handle the first. The forward pass handles the second.
The Backward Variant You Will See in Textbooks
Many textbooks, CLRS among them, use inclusive prefix sums and a backward placement pass. With inclusive sums, counts[v] holds one past the last index of key v's block. Walking the input from right to left and decrementing before writing fills each block from its end. The last record with key v takes the last slot, so the order is preserved.
def counting_sort_by_key_backward(items, key, k):
"""Stable counting sort using inclusive prefix sums and a backward pass."""
counts = [0] * (k + 1)
for item in items:
counts[key(item)] += 1
# Inclusive prefix sums: counts[v] is one past the last index for key v.
for v in range(1, k + 1):
counts[v] += counts[v - 1]
out = [None] * len(items)
for item in reversed(items): # backward pass fills each block from its end
kv = key(item)
counts[kv] -= 1
out[counts[kv]] = item
return out
people = [("ana", 2), ("bo", 1), ("cy", 2), ("di", 0)]
print(counting_sort_by_key_backward(people, lambda p: p[1], 2))
# [('di', 0), ('bo', 1), ('ana', 2), ('cy', 2)]Both versions produce the same output and cost the same. Use whichever one you can reason about more reliably, and do not mix their halves.
Edge Cases and Failure Modes
Keys outside 0..k
A key greater than k raises an IndexError in the counting pass, which is at least loud. A negative key is worse. Python treats counts[-1] as counts[k], so a key of -1 is silently counted as key k and the output is wrong with no error. If the keys come from data you do not control, check them first:
def checked_key(key, k):
"""Wrap a key function so out-of-range keys fail loudly."""
def wrapped(item):
kv = key(item)
if not (0 <= kv <= k):
raise ValueError(f"key {kv!r} outside 0..{k}")
return kv
return wrapped
try:
print(counting_sort_by_key([("x", -1), ("y", 0)], checked_key(lambda p: p[1], 1), 1))
except ValueError as e:
print("rejected:", e)
# rejected: key -1 outside 0..1A later chapter shows how to handle negative keys properly by shifting them.
Non-integer keys
A key of 2.0 raises a TypeError when it is used as a list index. A bool key is accepted silently, because True acts as 1. Make the key function return an int explicitly if there is any doubt.
Degenerate inputs
An empty list returns []. Every loop simply runs zero times, or k + 1 times over zeros. If all records share one key, there is a single block, and the output is a copy of the input in the same order. k = 0 is valid.
Key functions that are expensive or unstable
The key is computed twice per record, once when counting and once when placing. If key is slow, compute the keys once into a list and index into it. If key can return different values on the two calls, for example because it reads mutable state, the counts and the placements will disagree. Some slots will stay None, and others will be overwritten.
Testing Against a Trusted Reference
Python's built-in sorted is guaranteed to be stable. It is therefore a precise reference: for any input, a stable counting sort must match sorted(items, key=...) exactly, including the order of ties. The test below tags each record with its input position so that a tie in the wrong order makes the assertion fail.
import random
def counting_sort_by_key(items, key, k):
counts = [0] * (k + 1)
for item in items:
counts[key(item)] += 1
total = 0
for v in range(k + 1):
counts[v], total = total, total + counts[v]
out = [None] * len(items)
for item in items:
kv = key(item)
out[counts[kv]] = item
counts[kv] += 1
return out
random.seed(1)
for _ in range(2000):
n = random.randint(0, 30)
k = random.randint(0, 6)
items = [(random.randint(0, k), i) for i in range(n)] # (key, input position)
expected = sorted(items, key=lambda p: p[0])
assert counting_sort_by_key(items, lambda p: p[0], k) == expected
print("all tests passed")Small values of k make ties common, and ties are where stability bugs hide.
Cost Summary
| Pass | Time | Extra space |
|---|---|---|
| Count | O(n) | O(k) for `counts` |
| Prefix sums | O(k) | reuses `counts` |
| Place | O(n) | O(n) for `out` |
| Total | O(n + k) | O(n + k) |
The O(n) output buffer is the price of stability and of moving whole records. The next chapter looks at what happens to this cost when k is much larger than n.
Exercise
In the forward-pass version, suppose you replace for item in items: in the placement loop with for item in reversed(items): and change nothing else. Are the keys still in order? Is the sort still stable? Give the output for people.
Show answer
The keys are still in order, because each record still lands inside its key's block. The sort is no longer stable: each group of equal keys comes out in reverse input order. The output is [('di', 0), ('bo', 1), ('cy', 2), ('ana', 2)].
Exercise
You have a list of dicts like {"name": "ana", "age": 34}, with ages from 0 to 120. Write the call that stably sorts them by age with countingsortby_key, and state the size of the counts array.
Show answer
countingsortby_key(rows, lambda r: r["age"], 120). The counts array has k + 1 = 121 entries.
Exercise
A record's key function returns -2 and k = 5. What does countingsortby_key do, and why?
Show answer
It raises no error. counts[-2] refers to counts[4], so the record is counted, and later placed, as if its key were 4. The output is wrong without any warning. Validate keys or shift them to start at 0 to prevent this.