TExcelTAD
Home › Advanced & Succinct Data Structures › Integer Sorting beyond n lg n

Integer Sorting beyond n lg n

Sorting needs Ω(nlg⁡n)\Omega(n \lg n) 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 nn integers of ww 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 w=O(lg⁡n)w = O(\lg n)

Radix sort with digits of bb bits makes ⌈w/b⌉\lceil w / b \rceil passes of counting sort, each costing O(n+2b)O(n + 2^b). Choosing b=lg⁡nb = \lg n balances the two terms:

T(n,w)=O ⁣(wlg⁡n⋅n)T(n, w) = O\!\left(\frac{w}{\lg n} \cdot n\right)

So radix sort is linear when w=O(lg⁡n)w = O(\lg n), that is, when the keys are at most polynomial in nn. For w=64w = 64 and n=216n = 2^{16} 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.

python · try it yourself
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 b=lg⁡n=12b = \lg n = 12 the counters stop being negligible; the sweet spot is just below lg⁡n\lg n. Either way the count per key is Θ(w/lg⁡n)\Theta(w / \lg n), here larger than lg⁡n=12\lg n = 12: 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.

cpp · try it yourself
#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 nn inserts and nn successor queries of O(lg⁡w)O(\lg w) each:

O(nlg⁡w)=O(nlg⁡lg⁡U)O(n \lg w) = O(n \lg \lg U)

Asymptotically this beats nlg⁡nn \lg n whenever lg⁡w=o(lg⁡n)\lg w = o(\lg n), but it needs Θ(U)\Theta(U) 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.

python · try it yourself
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 lg⁡n=12\lg n = 12 comparisons. With 64-bit keys the predecessor approach only pays off when lg⁡n\lg n is well above 2(lg⁡w+1)2(\lg w + 1), and the constant per call is much larger than a comparison's.

What is known

The table lists the main results. "Linear space" means O(n)O(n) words. All of them are for the word-RAM with multiplication unless noted.

Algorithm Time Conditions
radix sort O(n⋅w/lg⁡n)O(n \cdot w / \lg n) deterministic; linear when w=O(lg⁡n)w = O(\lg n)
vEB / y-fast sort O(nlg⁡w)O(n \lg w) vEB arrays need O(2w)O(2^w) space; y-fast needs hashing (expected)
Kirkpatrick and Reisch (1984) O(nlg⁡(w/lg⁡n))O(n \lg (w / \lg n)) deterministic; reduces the key length by half per level
Andersson, Hagerup, Nilsson and Raman (1998), signature sort O(n)O(n) expected when w≥(lg⁡n)2+εw \ge (\lg n)^{2 + \varepsilon} for a constant ε>0\varepsilon > 0
Andersson et al. (1998), packed merging O(nlg⁡lg⁡n)O(n \lg \lg n) deterministic
Han (2002) O(nlg⁡lg⁡n)O(n \lg \lg n) deterministic, linear space
Han and Thorup (2002) O(nlg⁡lg⁡n)O(n \sqrt{\lg \lg n}) 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 O(n)O(n) is possible for every ww; the best general bound is Han and Thorup's O(nlg⁡lg⁡n)O(n \sqrt{\lg \lg n}) expected time.

The Kirkpatrick-Reisch idea (sketch)

Split each ww-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 w/2w/2-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 O(n)O(n). The recursion T(n,w)=T(n,w/2)+O(n)T(n, w) = T(n, w/2) + O(n) stops when w≤lg⁡nw \le \lg n, where radix sort is linear: O(nlg⁡(w/lg⁡n))O(n \lg(w / \lg n)) 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 nn keys can be sorted in n⋅S(n)n \cdot S(n) time, there is a priority queue with O(S(n))O(S(n)) time per operation, and conversely. With Han's sorting this gives deterministic priority queues with O(lg⁡lg⁡n)O(\lg \lg n) time per operation, and with Han and Thorup's, O(lg⁡lg⁡n)O(\sqrt{\lg \lg n}) 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 lg⁡n\lg n bits, how many passes does radix sort need for nn keys of ww bits?

  1. lg⁡n\lg n
  2. ⌈w/lg⁡n⌉\lceil w / \lg n \rceil
  3. ww
  4. lg⁡w\lg w

For which key lengths is integer sorting known to take O(n)O(n) (expected) time?

  1. For every ww
  2. For w=O(lg⁡n)w = O(\lg n) (radix sort) and for w≥(lg⁡n)2+εw \ge (\lg n)^{2+\varepsilon} (signature sort)
  3. Only for w=64w = 64
  4. Never; Ω(nlg⁡n)\Omega(n \lg n) is a lower bound

What does Thorup's equivalence between sorting and priority queues say?

  1. Priority queues are always faster than sorting
  2. Sorting nn keys in n⋅S(n)n \cdot S(n) time gives a priority queue with O(S(n))O(S(n)) time per operation, and vice versa
  3. Heaps are optimal on a word-RAM
  4. Sorting is O(n)O(n) if priority queues are O(1)O(1) amortized, but not conversely