Sub topic 6
Stable Counting Sort for Records with Keys
This chapter assumes you know how to build a count array (histogram), how exclusive prefix sums turn counts into starting positions, and what it means for a sort to be stable. Those ideas come from earlier chapters. Here they combine into one algorithm that sorts whole records, not just bare integers.
From Values to Records
The histogram version of counting sort writes values back from the counts. That works when the value is all you have. Real data is usually a record, such as a person with a name and an age, or an order with an ID and a priority. You want to sort by one integer field, the key, and keep each record whole.
You cannot rebuild a record from a count. The count tells you how many records have key 2, but not which ones. So the algorithm has to move the records themselves into place, and prefix sums tell it where each one goes.
The Algorithm
The function takes a key function that pulls an integer in 0..k out of each item.
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)]The algorithm makes three passes:
- Count how many items have each key.
- Replace each count with the index where that key's block starts in the output.
- Walk the input from front to back. Drop each item at its key's next free slot, then move that slot pointer forward by one.
Tracing the Example
| Step | Item | Key | Slot used | counts after |
|---|---|---|---|---|
| start | [0, 1, 2] | |||
| 1 | ana | 2 | 2 | [0, 1, 3] |
| 2 | bo | 1 | 1 | [0, 2, 3] |
| 3 | cy | 2 | 3 | [0, 2, 4] |
| 4 | di | 0 | 0 | [1, 2, 4] |
Records ana and cy both have key 2. ana comes first in the input, so it takes slot 2 before cy takes slot 3. Each key's block fills from left to right in input order, and that is why the sort is stable.
Common Errors
- Keys outside
0..k. A key larger thankraisesIndexError. A negative key is worse: Python indexes from the end of the list and silently gives wrong results. Check the key range, or shift the keys first. - Sorting in place. You need a separate output array. If you write into the input array, you overwrite records you have not read yet.
- Calling
keyrepeatedly when it is expensive. The code callskey(item)twice per item. If the key takes real work to compute, compute it once per item and store the results.
Radix sort depends on this stability. Each digit pass must keep the order that earlier passes set up.
Exercise
In countingsortby_key, change the placement loop to "for item in reversed(items):" and change nothing else. What does the people example print, and what property is lost?
Show answer
It prints [('di', 0), ('bo', 1), ('cy', 2), ('ana', 2)]. The reversed scan reaches cy before ana, so cy takes slot 2 and ana takes slot 3. Equal keys come out in reverse input order, so the sort is no longer stable.
Exercise
Use countingsortby_key to sort the words ["pear", "fig", "kiwi", "apple", "date"] by length, with ties kept in their original order. What call do you make, and what is the result?
Show answer
Call countingsortby_key(words, len, 5), because the longest word has 5 letters. The result is ['fig', 'pear', 'kiwi', 'date', 'apple'].