LOGBOOK

HELP

Quiz Entry - updated: 2026.11.27

How does lexicographic sort use $d$ passes of a stable sort, and why must it start with the last dimension?

It runs a stable sort once per dimension, from the last to the first: for i ← d downto 1: stableSort(S, Cᵢ), where $C_i$ compares tuples by their $i$-th component only. The final pass, on dimension 1, decides the order; tuples that tie there keep the order of the earlier passes, which is their order by the remaining dimensions. Time: $O(d \cdot T(n))$.

Five 3-tuples sorted by dimension 3, then 2, then 1; the key of each pass is highlighted

* After the pass on dimension i, the tuples are sorted lexicographically by dimensions i to 3. *

Why the backwards order works: after the pass on dimension 3, the list is sorted by dimension 3. The pass on dimension 2 sorts by dimension 2, and among tuples with equal second components the stable sort keeps the previous order, the order by dimension 3: now the list is sorted by (dimension 2, dimension 3). The last pass puts dimension 1 in front, so the result is sorted by $(x_1, x_2, x_3)$, which is the lexicographic order.

In the example, $(2,1,4)$ and $(2,4,6)$ tie in the last pass. They keep the order the pass on dimension 2 gave them, and since $1 < 4$, $(2,1,4)$ comes first, as the lexicographic order demands.

Each pass costs whatever the chosen stable sort costs, $T(n)$, so the whole sort takes $O(d \cdot T(n))$: $O(d\,n\log n)$ with merge-sort, and $O(d(n + N))$ with bucket-sort, which is radix-sort.

Go deeper:

From Quiz: ADS / Sorting Lower Bound, Bucket-Sort and Radix-Sort | Updated: Nov 27, 2026