Integer Sorting beyond n lg n
Sorting needs comparisons (decision trees). Integers are not just comparable things, though: on a word-RAM they can be split into digits, used as addresses and packed several to a word. How fast can integers of bits be sorted then? The question is one of the oldest in the field and is still open; this lesson collects what is known, states the bounds carefully, and runs the two simplest algorithms behind them.
Radix sort: linear when
Radix sort with digits of bits makes passes of counting sort, each costing . Choosing balances the two terms:
So radix sort is linear when , that is, when the keys are at most polynomial in . For and it needs four passes, against merge sort's 16 comparisons per key. The program counts the basic steps (one per key per pass, plus one per counter) for a few digit sizes.
import math, random
def radix_sort(a, w, b):
"""LSD radix sort of w-bit keys with b-bit digits; returns the sorted list and the step count."""
steps, mask = 0, (1 << b) - 1
for shift in range(0, w, b):
count = [0] * (1 << b)
for x in a:
count[(x >> shift) & mask] += 1
total = 0
for d in range(1 << b): # prefix sums: start of each digit's output range
count[d], total = total, total + count[d]
out = [0] * len(a)
for x in a: # forward pass with start positions: stable
d = (x >> shift) & mask
out[count[d]] = x
count[d] += 1
a = out
steps += 2 * len(a) + (1 << b)
return a, steps
rng = random.Random(1984)
w, n = 64, 1 << 12
data = [rng.getrandbits(w) for _ in range(n)]
print(f"n = {n}, w = {w}; merge sort needs about n lg n = {n * int(math.log2(n))} comparisons")
for b in [4, 8, 12, 16]:
out, steps = radix_sort(data, w, b)
assert out == sorted(data)
print(f"digits of {b:2} bits: {math.ceil(w / b):2} passes, {steps:7} steps, {steps / n:5.1f} per key")n = 4096, w = 64; merge sort needs about n lg n = 49152 comparisons
digits of 4 bits: 16 passes, 131328 steps, 32.1 per key
digits of 8 bits: 8 passes, 67584 steps, 16.5 per key
digits of 12 bits: 6 passes, 73728 steps, 18.0 per key
digits of 16 bits: 4 passes, 294912 steps, 72.0 per key
With the counters stop being negligible; the sweet spot is just below . Either way the count per key is , here larger than : for 64-bit keys and only 4096 of them, radix sort has no asymptotic advantage.
In C++
The same LSD radix sort on 64-bit keys with 16-bit digits, the common choice in practice for large arrays. It sorts a million keys in four passes and checks the result against std::sort.
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstdio>
#include <random>
#include <vector>
void radix_sort(std::vector<std::uint64_t>& a) {
std::vector<std::uint64_t> out(a.size());
for (int shift = 0; shift < 64; shift += 16) {
std::array<std::size_t, 65536> count{};
for (auto x : a) ++count[(x >> shift) & 0xFFFF];
std::size_t total = 0;
for (auto& c : count) { std::size_t t = c; c = total; total += t; }
for (auto x : a) out[count[(x >> shift) & 0xFFFF]++] = x; // stable
a.swap(out);
}
}
int main() {
std::mt19937_64 rng(1984);
std::vector<std::uint64_t> a(1'000'000);
for (auto& x : a) x = rng();
auto b = a;
radix_sort(a);
std::sort(b.begin(), b.end());
std::printf("n = %zu, 4 passes of 16 bits, equal to std::sort: %s\n", a.size(), a == b ? "yes" : "no");
std::printf("smallest %llu, largest %llu\n", static_cast<unsigned long long>(a.front()),
static_cast<unsigned long long>(a.back()));
}n = 1000000, 4 passes of 16 bits, equal to std::sort: yes
smallest 11802962818465, largest 18446721501909709704
Sorting with a predecessor structure
Insert all keys into a van Emde Boas tree or a y-fast trie, then walk from the minimum with SUCCESSOR. That is inserts and successor queries of each:
Asymptotically this beats whenever , but it needs space for the array version or hashing (expected time) for the compact ones. The program sorts with the compact vEB tree of this section and counts the calls.
import random
class VEB:
calls = 0
def __init__(self, k):
self.k, self.min, self.max = k, None, None
if k > 1: self.lo, self.clusters, self.summary = k // 2, {}, None
def insert(self, x):
VEB.calls += 1
if self.min is None: self.min = self.max = x; return
if x < self.min: x, self.min = self.min, x
if self.k > 1:
h, l = x >> self.lo, x & ((1 << self.lo) - 1)
c = self.clusters.get(h)
if c is None:
c = self.clusters[h] = VEB(self.lo); c.min = c.max = l
if self.summary is None: self.summary = VEB(self.k - self.lo)
self.summary.insert(h)
else: c.insert(l)
if x > self.max: self.max = x
def successor(self, x):
VEB.calls += 1
if self.min is not None and x < self.min: return self.min
if self.k == 1: return 1 if x == 0 and self.max == 1 else None
h, l = x >> self.lo, x & ((1 << self.lo) - 1)
c = self.clusters.get(h)
if c is not None and l < c.max: return (h << self.lo) | c.successor(l)
nxt = self.summary.successor(h) if self.summary else None
return None if nxt is None else (nxt << self.lo) | self.clusters[nxt].min
rng = random.Random(7)
w = 64
data = sorted({rng.getrandbits(w) for _ in range(5000)}, key=lambda x: x % 9973) # an unsorted order
v = VEB(w)
for x in data: v.insert(x)
out, x = [], v.min
while x is not None:
out.append(x); x = v.successor(x)
assert out == sorted(data)
print(f"n = {len(data)}, w = {w}: {VEB.calls} calls, {VEB.calls / len(data):.1f} per key; lg n = {len(data).bit_length() - 1}, 2(lg w + 1) = {2 * w.bit_length()}")n = 5000, w = 64: 64868 calls, 13.0 per key; lg n = 12, 2(lg w + 1) = 14
Thirteen calls per key, just under the bound of 14 for one insert and one successor, and about the same as comparisons. With 64-bit keys the predecessor approach only pays off when is well above , and the constant per call is much larger than a comparison's.
What is known
The table lists the main results. "Linear space" means words. All of them are for the word-RAM with multiplication unless noted.
| Algorithm | Time | Conditions |
|---|---|---|
| radix sort | deterministic; linear when | |
| vEB / y-fast sort | vEB arrays need space; y-fast needs hashing (expected) | |
| Kirkpatrick and Reisch (1984) | deterministic; reduces the key length by half per level | |
| Andersson, Hagerup, Nilsson and Raman (1998), signature sort | expected | when for a constant |
| Andersson et al. (1998), packed merging | deterministic | |
| Han (2002) | deterministic, linear space | |
| Han and Thorup (2002) | expected, linear space |
Combining the first and the signature-sort rows: sorting is linear for very short keys and for very long keys. The open question is whether is possible for every ; the best general bound is Han and Thorup's expected time.
The Kirkpatrick-Reisch idea (sketch)
Split each -bit key into its high half and low half. Group the keys by high half (with a hash table or a radix pass on the high half), keep the minimum of each group aside, and form one list of the distinct high halves together with the low halves of the other keys, all now -bit numbers, tagged with their group. Sort that list recursively, which sorts the high halves and, within each group, the low halves, and rebuild the sorted order from it in . The recursion stops when , where radix sort is linear: in total. It is the same "halve the key length" step as in van Emde Boas trees, applied to a whole batch at once.
Priority queues. Thorup (2007) proved that sorting and priority queues are equivalent on the word-RAM: if keys can be sorted in time, there is a priority queue with time per operation, and conversely. With Han's sorting this gives deterministic priority queues with time per operation, and with Han and Thorup's, expected. Dijkstra's algorithm on integer weights benefits directly (Dijkstra with priority queues).
Note: In practice, radix sort with 8- or 16-bit digits is the fast integer sort for large arrays of fixed-width keys, and comparison sorts win on small or nearly sorted inputs. The asymptotically fastest algorithms above are not used in practice: their constants are large and they rely on multiplication tricks that cost more than a cache miss saves.
Test yourself
With digits of bits, how many passes does radix sort need for keys of bits?
For which key lengths is integer sorting known to take (expected) time?
- For every
- For (radix sort) and for (signature sort)
- Only for
- Never; is a lower bound
What does Thorup's equivalence between sorting and priority queues say?
- Priority queues are always faster than sorting
- Sorting keys in time gives a priority queue with time per operation, and vice versa
- Heaps are optimal on a word-RAM
- Sorting is if priority queues are amortized, but not conversely