Sub topic 5
Turning Counts into Positions with Prefix Sums
This chapter assumes you know the histogram version of counting sort from the previous chapter, Python lists and loops, and Big-O notation.
The histogram version rebuilds the output by writing each value counts[v] times. That works for bare integers, but it throws away the original elements. If each element is a record with a key, you need to move the record itself, so you have to know where in the output each key's group begins. A prefix sum gives you that.
From "how many" to "where"
Suppose every key is in the range 0..k and counts[v] holds how many elements have key v. All elements with key 0 come first in the sorted output. Elements with key 1 come right after them, and so on. So the first slot for key v equals the number of elements with a key smaller than v:
start[v] = counts[0] + counts[1] + ... + counts[v-1]
This running total is called an exclusive prefix sum. "Exclusive" means it leaves out counts[v] itself.
Take the input [3, 1, 4, 1, 5, 2, 0] with k = 5:
| Key v | counts[v] | Exclusive prefix (start) | Inclusive prefix (end + 1) |
|---|---|---|---|
| 0 | 1 | 0 | 1 |
| 1 | 2 | 1 | 3 |
| 2 | 1 | 3 | 4 |
| 3 | 1 | 4 | 5 |
| 4 | 1 | 5 | 6 |
| 5 | 1 | 6 | 7 |
Key 1 appears twice, so it owns output slots 1 and 2, and key 2 starts at slot 3. The last inclusive value always equals n, the input length. That makes it a quick sanity check.
Placing elements directly
Once you have the start array, treat each entry as a cursor. For each input element, write it at its key's cursor, then move that cursor forward one slot.
def exclusive_prefix_sums(counts):
"""Return starts where starts[v] = sum of counts[0..v-1]."""
starts = [0] * len(counts)
total = 0
for v, c in enumerate(counts):
starts[v] = total
total += c
return starts
def counting_sort_positions(a, k):
"""Sort integers in 0..k by placing each one at its final index."""
counts = [0] * (k + 1)
for x in a:
counts[x] += 1
next_slot = exclusive_prefix_sums(counts)
out = [None] * len(a)
for x in a:
out[next_slot[x]] = x
next_slot[x] += 1
return out
data = [3, 1, 4, 1, 5, 2, 0]
counts = [1, 2, 1, 1, 1, 1]
print(exclusive_prefix_sums(counts)) # [0, 1, 3, 4, 5, 6]
print(counting_sort_positions(data, 5)) # [0, 1, 1, 2, 3, 4, 5]The placement loop never compares two elements. Each element costs one array lookup and one write. Computing the prefix sum is a single O(k) pass. The next chapter uses this same loop to move whole records by key.
Inclusive sums and the backward pass
Many textbooks, including CLRS, use an inclusive prefix sum instead. In an inclusive sum, counts[v] becomes one past the last slot for key v. That version scans the input from right to left, decrements the cursor first, and then writes. Both versions produce the same result. The difference is only where the cursor starts and which direction it moves.
Common errors
- Forgetting to advance the cursor. Equal keys then overwrite each other in the same slot.
- Computing the sum in place incorrectly.
counts[v] += counts[v-1]produces an inclusive sum, not an exclusive one. - Sizing the count array as k instead of k + 1. Then the largest key has no counter.
Exercise
For the input [2, 0, 2, 1, 2] with keys in 0..2, give the count array, the exclusive prefix sum array, and the output index each of the three 2s is written to, using a forward pass.
Show answer
counts = [1, 1, 3]. The exclusive prefix sums are [0, 1, 2]. Scanning forward, the first 2 (input index 0) goes to slot 2, the second 2 (input index 2) goes to slot 3, and the third 2 (input index 4) goes to slot 4. The 2s keep their input order.
Exercise
Why is the final inclusive prefix sum always equal to n, and how can you use that fact?
Show answer
The final inclusive sum adds up every count, and every input element was counted exactly once. If the total is not n, the counting step has a bug, for example a key outside 0..k or a skipped element. You can check it with an assertion before the placement loop.