Linear-Time Sorting
Counting sort, radix sort and bucket sort beat n log n by not comparing elements — when keys have structure you can exploit.
The Ω(n log n) bound applies only to comparison sorts. If keys are integers in a known range, or have digits you can inspect, you can sort in linear time by using the key values directly as array indices.
| Algorithm | Time | Space | Stable | Requirement |
|---|---|---|---|---|
| Counting sort | O(n + k) | O(n + k) | ✓ | Integer keys in a small range [0, k) |
| Radix sort | O(d·(n + b)) | O(n + b) | ✓ | Keys with d digits in base b |
| Bucket sort | O(n) average | O(n) | ✓* | Keys uniformly distributed |
Counting sort
Count how many times each key occurs, turn counts into prefix sums (each key's final position), then place elements — iterating from the end keeps it stable.
int[] countingSort(int[] a, int k) { // values in [0, k)
int[] count = new int[k];
for (int x : a) count[x]++;
for (int i = 1; i < k; i++) count[i] += count[i - 1]; // prefix sums = end positions
int[] out = new int[a.length];
for (int i = a.length - 1; i >= 0; i--) // backwards → stable
out[--count[a[i]]] = a[i];
return out;
}def counting_sort(a, k):
count = [0] * k
for x in a:
count[x] += 1
for i in range(1, k):
count[i] += count[i - 1]
out = [0] * len(a)
for x in reversed(a): # backwards -> stable
count[x] -= 1
out[count[x]] = x
return outfunction countingSort(a: number[], k: number): number[] {
const count = new Array(k).fill(0);
for (const x of a) count[x]++;
for (let i = 1; i < k; i++) count[i] += count[i - 1];
const out = new Array(a.length);
for (let i = a.length - 1; i >= 0; i--) out[--count[a[i]]] = a[i];
return out;
}Radix sort
Sort by the least significant digit first, then the next, and so on, using a stable sort (counting sort) for each digit. Stability ensures earlier digit orderings survive.
| Pass | Input | Sorted by |
|---|---|---|
| Start | 170 45 75 90 802 24 2 66 | — |
| 1 | 170 90 802 2 24 45 75 66 | ones digit |
| 2 | 802 2 24 45 66 170 75 90 | tens digit |
| 3 | 2 24 45 66 75 90 170 802 | hundreds digit ✓ |
With 32-bit integers sorted 8 bits at a time: 4 passes over n elements with 256 buckets — very fast for large arrays of integers, IP addresses, or fixed-length strings.
void radixSort(int[] a) { // non-negative ints, base 256
int[] out = new int[a.length];
for (int shift = 0; shift < 32; shift += 8) {
int[] count = new int[257];
for (int x : a) count[((x >>> shift) & 255) + 1]++;
for (int i = 0; i < 256; i++) count[i + 1] += count[i];
for (int x : a) out[count[(x >>> shift) & 255]++] = x;
System.arraycopy(out, 0, a, 0, a.length);
}
}def radix_sort(a, base=10):
if not a:
return a
exp, m = 1, max(a)
while m // exp:
buckets = [[] for _ in range(base)]
for x in a:
buckets[(x // exp) % base].append(x) # stable: preserves order
a = [x for b in buckets for x in b]
exp *= base
return afunction radixSort(a: number[]): number[] { // non-negative ints
let exp = 1;
const max = Math.max(0, ...a);
while (Math.floor(max / exp) > 0) {
const buckets: number[][] = Array.from({ length: 10 }, () => []);
for (const x of a) buckets[Math.floor(x / exp) % 10].push(x);
a = buckets.flat();
exp *= 10;
}
return a;
}Bucket sort
Distribute n values into n buckets by range (e.g. floats in [0, 1) go to bucket ⌊n·x⌋), sort each small bucket (insertion sort), then concatenate. With uniformly distributed input each bucket holds O(1) elements → O(n) average; adversarial input degrades to the inner sort's worst case.
- Non-comparison sorts escape Ω(n log n) by indexing with key values.
- Counting sort: O(n + k), stable, for small integer ranges.
- Radix sort: stable digit-by-digit passes, O(d·(n + b)).
- Bucket sort: O(n) average for uniformly distributed data.
QMaximum gap between successive elements in sorted order, in O(n).hard
Pigeonhole: with n numbers between min and max, the maximum gap is at least (max−min)/(n−1). Use n−1 buckets of that width, tracking only each bucket's min and max. The answer is the largest difference between one non-empty bucket's max and the next non-empty bucket's min.
QWhy must radix sort process the least significant digit first with a stable sort?medium
After sorting by digit d, elements equal at d must stay in the order established by the less significant digits. A stable inner sort guarantees that, so after the last (most significant) pass the whole key is ordered.