Sub topic 2
Sorting Without Comparisons: Integer Keys in a Known Range
This chapter assumes you can read Python lists and loops, know Big-O notation, and remember the result from the previous chapter: any sort that learns about its input only by comparing pairs of elements needs Ω(n log n) comparisons in the worst case.
The Loophole in the Lower Bound
The lower bound depends on one assumption. The algorithm can only ask questions of the form "is a[i] < a[j]?", and each answer is yes or no. A sequence of such yes/no answers has to tell apart all n! possible input orderings, which takes about log₂(n!) ≈ n log n questions.
If you know more about the keys, you can ask more useful questions. Suppose every key is an integer between 0 and k. Then you can use the key itself as an array index. Reading slots[key] picks one of k + 1 locations in a single step. A comparison picks one of only 2 outcomes.
Because the decision-tree argument assumes two-way branching, it does not apply here. That is how counting sort and radix sort can run in linear time.
What Qualifies as a Bounded Integer Key
A key is the part of a record you sort by. You can index with it if you can map each key to an integer in a small range 0..k, and the mapping keeps the order, so a smaller key always gets a smaller index.
| Data | Key range | Usable directly? |
|---|---|---|
| Exam scores | 0..100 | Yes |
| Bytes | 0..255 | Yes |
| Ages in years | 0..130 | Yes |
| Years 1900–2025 | subtract 1900 to get 0..125 | Yes, after an offset |
| 64-bit integers | 0..2⁶⁴ − 1 | No, the range is too large (later chapters break these into digits) |
| Arbitrary floats or strings | unbounded | Not without a transformation |
The size of k matters as much as the type. An array with k + 1 slots costs O(k) memory and O(k) time to scan. With 10 keys and k = 2⁶⁴, the method is useless.
Direct Addressing: A First Taste
Here is the indexing idea in its simplest form. It sorts records whose keys are distinct integers in a known range. Each record goes into the slot named by its key, and a single left-to-right scan reads them back in order.
def sort_distinct_keys(items, key, lo, hi):
"""Sort items whose key(item) values are distinct integers in lo..hi."""
slots = [None] * (hi - lo + 1)
for item in items:
kv = key(item)
if not lo <= kv <= hi:
raise ValueError(f"key {kv} outside range {lo}..{hi}")
if slots[kv - lo] is not None:
raise ValueError(f"duplicate key {kv}")
slots[kv - lo] = item
return [item for item in slots if item is not None]
runners = [("kai", 1987), ("lu", 1975), ("mo", 2001), ("ny", 1990)]
print(sort_distinct_keys(runners, lambda r: r[1], 1970, 2010))
# [('lu', 1975), ('kai', 1987), ('ny', 1990), ('mo', 2001)]The function never compares two runners. It does n placements and one scan over k + 1 slots, so it runs in O(n + k) time.
Common Errors
- Forgetting the offset. Keys in 1970..2010 need
kv - loas the index. Without it you either allocate 2011 slots or index past the end. - Assuming the range. If one key falls outside lo..hi, Python either raises
IndexErroror, for negative indices, writes to the wrong slot without any error. Validate the range at the boundary, as the code above does. - Duplicates. One slot per key cannot hold two records with the same key. Handling duplicates correctly is the job of counting sort in the next chapter.
Exercise
In sortdistinctkeys, a caller passes lo=0 but one key is -3, and the range check has been removed. What goes wrong, and why does Python not raise an error?
Show answer
The index kv - lo is -3, and Python treats negative indices as counting from the end of the list. The record gets written into slots[len(slots) - 3], which is the slot for a large key. The output is then silently misordered. Checking that lo <= kv <= hi prevents this.
Exercise
You need to sort 1,000 records by a 32-bit unsigned ID. Why is direct indexing on the full ID a poor choice, and what does that suggest?
Show answer
k is about 4.3 billion, so the slot array would need billions of entries and O(k) time to scan, far more than the O(n log n) a comparison sort spends on 1,000 items. This suggests breaking the ID into smaller digits that each have a small range, which is the idea behind radix sort.