The price: k is the key space
Counting sort ordered 100,000 items in 3 ms without a single comparison. The obvious question: why not use it for everything?
Try applying it to Title.
k is the size of the key space
The count array needs one slot for every possible key value.
| key | k | the count array |
|---|---|---|
Rating (0–100) |
101 | 101 slots |
Year (1900–2030) |
131 | 131 slots |
int32 |
4,294,967,296 | 4.3 billion slots — 34 GB |
Title, up to 20 characters |
? | you compute it in the drills |
The third row is already impossible. The fourth is not "large" — it is meaningless, and the drills show you by how much.
The point is simple: counting sort is not a faster sort. It is a sort for a different problem — one where the key is a small integer from a known range.
Three preconditions, all mandatory
- The key is an integer, or convertible to one.
- The range is known in advance — when you write the code, not after inspecting the data.
- k is comparable to n. When k ≫ n, O(n + k) becomes O(k), and that is no longer a fast sort — it is a large allocation.
A comparison sort needs none of these. That is why comparison sorts are used everywhere and counting sort only where the conditions hold.
And in your library
Of Item's four fields, two are usable by counting sort: Rating and
Year. Title and Artist are not, today or ever.
That ratio — two out of four — is the real answer to "why not use it for everything".
The third condition is deceptive because O(n + k) looks linear. It is linear — in two quantities. The notation does not hide k; it is simply easy to read as though k were small. At n = 100 and k = 4,000,000,000, that "linear" sort allocates 34 GB to order a hundred items.