Sub topic 2
Sorting Without Comparisons: Integer Keys in a Known Range
The previous chapter showed that any algorithm that learns about its input only by comparing pairs of elements needs Ω(n log n) comparisons in the worst case. This chapter explains how to get around that bound. The trick is to give up generality: we sort only items whose keys are small integers, and we use each key directly as an array index.
This chapter assumes you can read Python lists, loops, and functions, that you know Big-O notation, and that you have met at least one comparison sort such as merge sort. You do not need to know counting sort yet. The next chapter builds it.
What the Lower Bound Actually Assumes
The Ω(n log n) proof uses a decision tree. Each internal node asks one question, "is a[i] < a[j]?", and branches two ways. A tree that can tell apart all n! input orderings needs at least n! leaves, so its height is at least log₂(n!), which is Θ(n log n).
The proof depends on one assumption: the only operation that inspects element values is a two-way comparison. Any operation that pulls more than one bit of information out of a key in a single step falls outside the model.
Array indexing is such an operation. If a key is an integer v between 0 and k, then the expression table[v] jumps to one of k + 1 memory locations in constant time. That is a (k + 1)-way branch, not a two-way one. One indexing step can place an element among k + 1 possibilities, where a comparison can only split the possibilities in two.
This does not break the lower bound. It steps outside the conditions the bound was proved under. The cost model changes too. Comparison sorts are analyzed by counting comparisons, while integer sorts are analyzed on the word RAM, where arithmetic, shifts, and array access on machine-sized integers each take O(1) time.
A First Sort That Never Compares Elements
Suppose the input holds distinct integers, all in the range 0..k. You can sort them with a boolean array:
def sort_distinct(a, k):
"""Sort distinct integers in 0..k without comparing elements to each other."""
present = [False] * (k + 1)
for x in a:
present[x] = True
return [v for v in range(k + 1) if present[v]]
print(sort_distinct([7, 2, 9, 0, 4], 9)) # [0, 2, 4, 7, 9]No line compares one input element with another. The first loop writes each value into its own slot. The second loop walks the slots in index order, and index order is sorted order. The if present[v] test checks a stored bit and never looks at another element. The range(k + 1) loop compares a counter against a bound, which is loop control and not a comparison between keys.
The running time is O(n) for the first loop plus O(k) for the second, so O(n + k) in total. When k is O(n), that is linear.
This version is a toy. It loses duplicates, since setting present[3] = True twice leaves no record of the second 3, and it cannot carry data attached to a key. The next chapters fix both problems: counting sort replaces the booleans with counts, and the prefix-sum version moves whole records. All of them rely on the same idea you see here. The key's value tells you where the item goes.
What "Integer Keys in a Known Range" Means
Each of these algorithms requires three things.
- A key function. Every item has a key,
key(item), that decides its sorted position. The item can be anything: a tuple, an object, a database row. - Integer keys. The key must be an integer, or something that maps to an integer while keeping its order.
- A known, bounded range. Before sorting, you need bounds lo and hi with lo ≤ key ≤ hi for every item. Shifting by lo gives keys in 0..k, where k = hi − lo. The algorithm allocates an array of size k + 1.
The range is the condition that limits these algorithms the most. The table in the next section shows that many real keys pass all three tests. A few, including some that look like integers, do not.
Which Keys Qualify
| Key type | Natural range | Map to 0..k | Fits directly? |
|---|---|---|---|
| Byte value | 0..255 | identity | Yes, k = 255 |
| Lowercase letter | 'a'..'z' | `ord(c) - ord('a')` | Yes, k = 25 |
| Exam score | 0..100 | identity | Yes, k = 100 |
| Age in years | 0..130 | identity | Yes, k = 130 |
| Day within a known year | Jan 1..Dec 31 | days since Jan 1 | Yes, k ≤ 365 |
| Enum or category | fixed set of labels | position in a fixed list | Yes, k = labels − 1 |
| Signed temperature | −90..60 | `t + 90` | Yes, k = 150 |
| 32-bit user ID | 0..2³² − 1 | identity | Range too large for one array |
| 64-bit integer | ±9.2 × 10¹⁸ | offset | No, needs radix sort |
| Arbitrary string | unbounded | none directly | No, needs MSD radix or a comparison sort |
| Float | huge, non-uniform | bit tricks | Not directly |
The 32-bit row teaches an important lesson. Those keys are integers and their range is known, but an array of 2³² counters takes 16 GiB at 4 bytes each. "Known range" is not enough. The range has to be small compared with the memory you have and with n. Radix sort, covered later, handles large ranges by splitting the key into small digits. Each digit is a small-range integer key on its own.
Mapping Keys into 0..k
Most real keys need a short mapping step. The mapping must be order-preserving: if a sorts before b, then key(a) < key(b) must hold, and equal items must get equal keys.
from datetime import date
def letter_key(ch):
"""Map 'a'..'z' to 0..25."""
return ord(ch) - ord("a")
def offset_key(x, lo):
"""Map lo..hi to 0..hi-lo."""
return x - lo
def day_key(d, start):
"""Map dates on or after start to days elapsed since start."""
return (d - start).days
SIZES = ["XS", "S", "M", "L", "XL"]
SIZE_INDEX = {label: i for i, label in enumerate(SIZES)}
def size_key(label):
"""Map clothing sizes to 0..4 by their position in the fixed order."""
return SIZE_INDEX[label]
print(letter_key("d")) # 3
print(offset_key(-12, -90)) # 78
print(day_key(date(2026, 3, 1), date(2026, 1, 1))) # 59
print(sorted(["L", "XS", "M"], key=size_key)) # ['XS', 'M', 'L']The size example needs a mapping. Comparing the strings "L", "M", "XS" alphabetically gives the wrong order. Mapping them to positions in a fixed list both orders them correctly and makes them usable as indices.
Finding the Range When You Don't Know It
Sometimes the bounds come from the domain, such as bytes or exam scores. Sometimes you have to measure them:
def key_range(items, key):
"""Return (lo, hi) over all keys, or None for empty input."""
it = iter(items)
try:
first = key(next(it))
except StopIteration:
return None
lo = hi = first
for item in it:
v = key(item)
if v < lo:
lo = v
elif v > hi:
hi = v
return lo, hi
print(key_range([(“x”, 40), ("y", 7), ("z", 19)], lambda p: p[1]) if False else key_range([("x", 40), ("y", 7), ("z", 19)], lambda p: p[1]))
# (7, 40)This scan does compare keys, but it makes at most 2(n − 1) comparisons, which is O(n). That does not contradict the lower bound. Finding a minimum and maximum is far easier than sorting, and the linear-time claim stays valid. Do this scan once, before sorting, and size the array as hi − lo + 1.
Common Errors
- Off-by-one array size. Keys in 0..k need
k + 1slots. Allocating[0] * kraisesIndexErroron the largest key, which is often the case your tests miss. - Forgetting the offset for negative keys. In Python,
table[-3]does not raise an error. It silently reads the third slot from the end, so the data gets corrupted with no warning. Always shift by lo first. - Non-order-preserving mappings. Using
hash(x) % mas a key spreads values into a small range but destroys their order. The output is grouped by key, not sorted. - Treating "integer" as "small". A column of IDs or timestamps is integer-valued, but its range may be billions. Check k before you allocate.
- Rounding floats into integer keys.
int(x * 100)maps prices to cents, but two different floats can map to the same key, and float error can put a value in the neighboring bucket. Use this only when the precision loss is acceptable and well defined.
Where This Leads
You now have the precondition that every later chapter builds on. If keys are integers in 0..k, a key can serve directly as an array index, and one indexing step decides among k + 1 positions. Counting sort turns this into a full sort that keeps duplicates. Prefix sums and stability let it move records along with their keys. Radix sort applies the same idea one digit at a time when the full range is too large.
Exercise
You need to sort 2 million log records by HTTP status code (values 100 to 599). Give the key mapping into 0..k, the value of k, and the size of the array you would allocate. Is the resulting sort linear in n?
Show answer
Map each code c to c − 100, so keys lie in 0..499 and k = 499. Allocate k + 1 = 500 slots. Since k is a small constant compared with n = 2,000,000, the O(n + k) cost is effectively O(n), so the sort is linear.
Exercise
A teammate sorts temperatures in −40..50 with sort_distinct(temps, 50) and gets no error, but the output is wrong. Explain what happened and how to fix it.
Show answer
Negative values such as −3 index the list from the end in Python (present[-3] is slot 48), so they silently mark the wrong slots and no IndexError occurs. In addition, the function loses duplicate temperatures. The fix is to shift by the minimum (use t + 40, so k = 90) and to use a sort that keeps counts or records, such as counting sort, instead of a boolean presence array.
Exercise
Why doesn't the Ω(n log n) lower bound apply to sort_distinct, even though its loop runs over a range and checks a condition?
Show answer
The lower bound covers algorithms that gain information about keys only through pairwise comparisons between elements. sort_distinct never compares two input elements. It uses each key as an array index, a (k + 1)-way branch done in O(1) on the word RAM. The range loop and the present[v] test check a loop counter and stored bits, not key against key, so the decision-tree argument does not apply.