No algorithm that sorts by comparing elements can beat Ω(n log n). Counting sort and bucket sort sidestep that limit by never comparing elements at all: they use each key's value as an array index. Counting sort sorts integers from a small range in O(n + k) time, and bucket sort sorts uniformly distributed numbers in expected O(n). This lesson also proves the comparison lower bound and compares every sorting algorithm on the site side by side.
Think of it like
Pigeonholes in a mail room
A mail clerk does not compare letters with each other. Each letter goes straight into the pigeonhole for its street number, and at the end the clerk empties the pigeonholes in order. With 100 pigeonholes this is lightning fast. With one pigeonhole per possible ZIP code on Earth, the wall of empty boxes becomes the problem: that is counting sort's trade-off between n and k.
Counting instead of comparing
Suppose every key is an integer in [0, k). If you know that 7 keys are smaller than 5, then the first 5 must go to output index 7, without ever comparing it with anything. Counting sort computes exactly those counts with one pass to build a histogram and one pass of Prefix Sums & Difference Arrays, then places every element directly into its final slot.
How counting sort works
- 1
Count
Allocate
count[0..k-1]filled with zeros, then for every elementxdocount[x] += 1. - 2
Prefix sums
Replace each count with a running total:
count[v] += count[v - 1]. Nowcount[v]is the number of keys≤ v, so the last copy ofvbelongs at indexcount[v] - 1. - 3
Place right to left
Scan the input from the last element to the first. For each
x, decrementcount[x]and writextoout[count[x]]. - 4
Copy back
outis sorted. Copy it into the original array if an in-place interface is needed.
| Value v | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| count[v] (histogram) | 2 | 0 | 2 | 3 | 0 | 1 |
| count[v] after prefix sums (keys ≤ v) | 2 | 2 | 4 | 7 | 7 | 8 |
| Output slots for v | 0..1 | none | 2..3 | 4..6 | none | 7 |
[2, 5, 3, 0, 2, 3, 0, 3] (k = 6). The output is [0, 0, 2, 2, 3, 3, 3, 5].def counting_sort_by_key(items: list, key, k: int) -> list:
"""Stable sort of items whose key(item) is an integer in [0, k)."""
count = [0] * k
for it in items:
count[key(it)] += 1
for v in range(1, k):
count[v] += count[v - 1]
out = [None] * len(items)
for it in reversed(items): # right to left: equal keys keep their order
count[key(it)] -= 1
out[count[key(it)]] = it
return out
people = [("Ana", 31), ("Bo", 25), ("Cy", 31), ("Di", 25)]
print(counting_sort_by_key(people, key=lambda p: p[1], k=130))
# [('Bo', 25), ('Di', 25), ('Ana', 31), ('Cy', 31)] Bo before Di, Ana before CyComplexity, and when k is too big
Counting takes O(n), the prefix sums take O(k), and placement takes O(n), for O(n + k) time and O(n + k) extra space. That is linear when k = O(n). When the key range dwarfs the number of elements, the k term dominates both time and memory.
Exam scores
k = 101
0 to 100: perfect fit
Bytes / ASCII
k = 256
a classic radix digit
Human ages
k ≈ 130
millions of records, tiny table
32-bit integers
16 GiB
2³² counters × 4 bytes: impractical
- Good fits: grades, ages, ratings, bytes and characters, small enums, day-of-year, histogram problems such as the H-index.
- Bad fits: arbitrary 32- or 64-bit integers, floating-point numbers, strings as whole keys. Use Radix Sort (counting sort one digit at a time) or a comparison sort instead.
- Rule of thumb: worth it when
kis at most a small multiple ofn, and the count array fits comfortably in cache.
Bucket sort
Bucket sort generalizes the pigeonhole idea to real numbers. For n values spread uniformly over [0, 1), create n buckets, drop each value x into bucket ⌊n·x⌋, sort each bucket with insertion sort, and concatenate the buckets in order. Because bucket i covers the range [i/n, (i+1)/n), everything in an earlier bucket is smaller than everything in a later one.
| Bucket | Range | Contents | After sorting |
|---|---|---|---|
| 1 | [0.1, 0.2) | 0.17, 0.12 | 0.12, 0.17 |
| 2 | [0.2, 0.3) | 0.26, 0.21, 0.23 | 0.21, 0.23, 0.26 |
| 3 | [0.3, 0.4) | 0.39 | 0.39 |
| 6 | [0.6, 0.7) | 0.68 | 0.68 |
| 7 | [0.7, 0.8) | 0.78, 0.72 | 0.72, 0.78 |
| 9 | [0.9, 1.0) | 0.94 | 0.94 |
[0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68] with 10 buckets (empty buckets omitted).With uniform input each bucket receives one element on average. Insertion sort on a bucket of size nᵢ costs O(nᵢ²), and for this distribution E[nᵢ²] = 2 − 1/n, a constant. Summed over n buckets, the expected sorting work is linear.
Shines when
- Keys are spread roughly evenly over a known range
- You can map a key to its bucket in O(1)
- Buckets can be processed in parallel or on separate machines
Fails when
- Keys cluster: if everything lands in one bucket, insertion sort makes it O(n²)
- The range or distribution is unknown in advance
- Memory for n buckets (lists) is a concern
The Ω(n log n) lower bound for comparison sorts
A comparison sort learns about its input only by asking questions of the form "is a[i] ≤ a[j]?". Any such algorithm, on inputs of size n, can be drawn as a decision tree: each internal node is a comparison, each branch is an answer, and each leaf is the permutation the algorithm outputs. Running the algorithm is following one root-to-leaf path, so the worst-case number of comparisons is the tree's height.
| Comparison answers | Sorted order | Comparisons |
|---|---|---|
| a ≤ b, b ≤ c | a, b, c | 2 |
| a ≤ b, b > c, a ≤ c | a, c, b | 3 |
| a ≤ b, b > c, a > c | c, a, b | 3 |
| a > b, a ≤ c | b, a, c | 2 |
| a > b, a > c, b ≤ c | b, c, a | 3 |
| a > b, a > c, b > c | c, b, a | 3 |
Every one of the n! input orderings needs its own leaf (otherwise two different inputs would get the same rearrangement, and one of them would come out unsorted). A binary tree of height h has at most 2ʰ leaves, so:
n = 3
3
⌈log₂ 6⌉ comparisons, minimum worst case
n = 10
22
⌈log₂ 3,628,800⌉
n = 1,000,000
≈ 18.5 M
log₂(n!) comparisons at least
Every sorting algorithm on this site, compared
| Algorithm | Best | Average | Worst | Extra space | Stable | In-place | Adaptive |
|---|---|---|---|---|---|---|---|
| Bubble Sort | O(n) | O(n²) | O(n²) | O(1) | Yes | Yes | Yes (early exit) |
| Selection Sort | O(n²) | O(n²) | O(n²) | O(1) | No | Yes | No |
| Insertion Sort | O(n) | O(n²) | O(n²) | O(1) | Yes | Yes | Yes: Θ(n + inversions) |
| Shell sort (Knuth gaps) | O(n log n) | depends on gaps | O(n^1.5) | O(1) | No | Yes | Partly |
| Merge Sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes | No | No (O(n) with the sorted-halves check) |
| Quick Sort | O(n log n) | O(n log n) | O(n²) | O(log n) | No | Yes | No |
| Heap Sort | O(n log n) | O(n log n) | O(n log n) | O(1) | No | Yes | No |
| Counting sort | O(n + k) | O(n + k) | O(n + k) | O(n + k) | Yes | No | No |
| Bucket sort | O(n) | O(n) | O(n²) | O(n) | Yes | No | No |
| Radix Sort (LSD) | O(d·(n + b)) | O(d·(n + b)) | O(d·(n + b)) | O(n + b) | Yes | No | No |
| Timsort | O(n) | O(n log n) | O(n log n) | O(n) | Yes | No | Yes: natural runs |
| Introsort | O(n log n) | O(n log n) | O(n log n) | O(log n) | No | Yes | No |
- General-purpose, fastest on average: quick sort, in practice introsort or pdqsort.
- Need stability or a guaranteed worst case with memory to spare: merge sort, in practice Timsort.
- Guaranteed O(n log n) with O(1) extra memory: heap sort.
- Tiny or nearly-sorted arrays: insertion sort.
- Small integer keys: counting sort. Fixed-width integers or strings: radix sort. Uniform real numbers: bucket sort.
- Writes are expensive: selection sort (at most n − 1 swaps).
Complexity
| Algorithm | Time | Space | Notes |
|---|---|---|---|
| Counting sort | O(n + k) | O(n + k) | k = size of the key range; stable |
| Bucket sort (average) | O(n) | O(n) | Uniformly distributed keys, n buckets |
| Bucket sort (worst) | O(n²) | O(n) | All keys in one bucket, sorted by insertion sort |
| Any comparison sort | Ω(n log n) | Lower bound from the decision-tree argument |
Counting and bucket sort avoid the comparison lower bound by indexing with key values, at the cost of assumptions about the keys.
Implementation
Histogram, prefix sums, then right-to-left placement. Works for any integer range (including negatives) by offsetting with the minimum.
def counting_sort(a: list[int]) -> list[int]:
if not a:
return a
lo, hi = min(a), max(a)
count = [0] * (hi - lo + 1) # k = hi - lo + 1 counters
for x in a:
count[x - lo] += 1 # 1. histogram
for v in range(1, len(count)):
count[v] += count[v - 1] # 2. count[v] = number of keys <= v
out = [0] * len(a)
for x in reversed(a): # 3. right to left keeps it stable
count[x - lo] -= 1
out[count[x - lo]] = x
a[:] = out # 4. copy back
return aKey takeaways
- Counting sort uses a histogram plus prefix sums to place each element directly: O(n + k) time and space, stable when filled right to left.
- It is only practical when the key range k is not much larger than n; for wide keys, use radix sort or a comparison sort.
- Bucket sort splits uniformly distributed values into n buckets for expected O(n) time, but degrades to O(n²) when keys cluster.
- Any comparison sort needs at least log₂(n!) = Ω(n log n) comparisons in the worst case, by the decision-tree argument.
- Non-comparison sorts escape that bound by indexing with key values, trading generality for assumptions about the keys.
Common pitfalls
- Allocating a count array sized by the maximum value (or the full integer range) when only a narrow band of values occurs; offset by the minimum.
- Filling the output left to right after computing inclusive prefix sums, which reverses equal keys and breaks stability.
- Using counting sort on huge key ranges (k ≫ n), where the O(k) time and memory dwarf an O(n log n) sort.
- Using bucket sort on skewed data without adapting the bucket boundaries, which piles everything into a few buckets.
Interview tips
- When values are bounded (scores, ages, characters, colors, frequencies up to n), mention an O(n + k) counting approach before reaching for a comparison sort.
- Be able to sketch the decision-tree proof: n! leaves, at most 2ʰ leaves at height h, so h ≥ log₂(n!) = Ω(n log n).
- Bucket-by-frequency (an array of lists indexed by count) solves Top K Frequent Elements in O(n), a common follow-up to the heap solution.
Real-world applications
- Histogram-based processing in image tools (sorting or equalizing 8-bit pixel intensities).
- The per-digit pass of radix sort, and suffix array construction.
- Sorting records by small keys: grades, ages, ratings, priorities, dates within a year.
- Distributed sorting (sample sort, TeraSort), where machines act as buckets for key ranges.
Practice problems
Test yourself
In the placement phase of counting sort, why is the input scanned from right to left?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.