Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

Sorting Networks & Parallel Sorting

The 0–1 principle, bitonic sort and the AKS network.

A sorting network fixes all of its comparisons before it sees the data, so they can run in parallel and the running time never depends on the input. Proving that nine inputs need exactly 25 comparators took a computer search in 2014. The asymptotically optimal network, from 1983, has depth O(log⁡n)O(\log n) but constants so large that Batcher's networks from 1968, of depth O(log⁡2n)O(\log^2 n), remain the ones used in practice, for example to sort small blocks inside vector registers.

What you’ll learn

  • Define comparator networks with their size and depth, and derive the lower bounds ⌈log⁡2n!⌉\lceil \log_2 n! \rceil on size and ⌈log⁡2n⌉\lceil \log_2 n \rceil on depth.
  • State and prove the 0–1 principle, and use it to verify a network on nn wires with 2n2^n tests.
  • Build Batcher's bitonic and odd–even merge sorting networks and count their comparators and depth.
  • Summarize what is known about optimal small networks, the AKS network and parallel sorting, and what is still open.

Comparators, size and depth

Four wires need five comparators in three layers: {[0:1],[2:3]}\{[0{:}1], [2{:}3]\} sorts the two pairs; {[0:2],[1:3]}\{[0{:}2], [1{:}3]\} sends the overall minimum to wire 0 and the maximum to wire 3; and [1:2][1{:}2] orders the middle two. Two lower bounds hold for every network:

DerivationLower bounds on size and depth
  1. size  ≥  ⌈log⁡2n!⌉\text{size} \;\ge\; \lceil \log_2 n! \rceil

    Size. A network is a comparison sort whose comparisons happen not to depend on earlier outcomes, so the decision-tree bound applies:

  2. 2depth  ≥  n⟹depth  ≥  ⌈log⁡2n⌉2^{\text{depth}} \;\ge\; n \quad\Longrightarrow\quad \text{depth} \;\ge\; \lceil \log_2 n \rceil

    Depth. After dd layers, the value on any wire depends on at most 2d2^d input wires, since each comparator combines two. Wire 0 must be able to receive the minimum from any of the nn input wires:

The simplest sorting network is odd–even transposition sort: nn rounds that alternately compare the pairs (0,1),(2,3),…(0, 1), (2, 3), \dots and (1,2),(3,4),…(1, 2), (3, 4), \dots It uses n(n−1)/2n(n-1)/2 comparators in depth nn, which is wasteful, but every comparator joins neighboring wires, so it suits a line of processors that can talk only to their neighbors.

nncounting bound ⌈log⁡2n!⌉\lceil \log_2 n! \rceilfewest comparatorsstatus
455optimal
81619optimal
91925optimal: Floyd's network (1964), proved by Codish et al. (2014)
102229optimal: Waksman's network (1969), proved by Codish et al. (2014)
112635optimal, proved by Harder (2020)
122939optimal, proved by Harder (2020)
164560 best knownoptimal size unknown
The optimality proofs are computer searches over huge spaces of partial networks. Obliviousness has a price: an adaptive algorithm sorts 12 keys with 30 comparisons in the worst case, while a network needs 39. For depth, Bundala and Závodný (2014) used a SAT solver to prove that the networks of minimum depth listed in Knuth's book for up to 16 inputs are optimal.

The 0–1 principle

Checking a network on all n!n! orders is hopeless beyond tiny nn. A remarkable theorem reduces the check to inputs made of 0s and 1s only, and it is also the standard tool for proving networks correct.

DerivationProof
  1. [i:j] applied to f(x)  =  f applied to ([i:j] applied to x)[i{:}j] \text{ applied to } f(x) \;=\; f \text{ applied to } \big([i{:}j] \text{ applied to } x\big)

    Monotone maps commute with comparators. If ff is nondecreasing, then f(min⁡(a,b))=min⁡(f(a),f(b))f(\min(a, b)) = \min(f(a), f(b)) and likewise for max:

  2. N(f(x))=f(N(x))N\big(f(x)\big) = f\big(N(x)\big)

    So they commute with networks. By induction over the comparators, running the network on f(x0),…,f(xn−1)f(x_0), \dots, f(x_{n-1}) yields f(y0),…,f(yn−1)f(y_0), \dots, f(y_{n-1}), where yy is the network's output on xx.

  3. f(yi)=1  >  0=f(yi+1)f(y_i) = 1 \;>\; 0 = f(y_{i+1})

    Contradiction. Suppose the network fails on some xx: its output has yi>yi+1y_i > y_{i+1} for some ii. Take the 0–1 threshold f(t)=1f(t) = 1 if t≥yit \ge y_i and 0 otherwise, which is nondecreasing. The network maps the 0–1 input f(x)f(x) to f(y)f(y), which has f(yi)=1f(y_i) = 1 before f(yi+1)=0f(y_{i+1}) = 0: a binary input the network fails to sort.

python
def sorts_all_binary(net, n):
    """0-1 principle: a network on n wires sorts every input iff it sorts all 2**n inputs of 0s and 1s."""
    for bits in range(1 << n):
        xs = [(bits >> i) & 1 for i in range(n)]
        for i, j in net:                       # comparator (i, j) with i < j: the minimum goes to wire i
            if xs[i] > xs[j]:
                xs[i], xs[j] = xs[j], xs[i]
        if any(xs[i] > xs[i + 1] for i in range(n - 1)):
            return False
    return True

four = [(0, 1), (2, 3), (0, 2), (1, 3), (1, 2)]
print(sorts_all_binary(four, 4))                        # True: 16 tests stand in for 24 permutations
print(sorts_all_binary([(0, 1), (2, 3), (1, 2)], 4))    # False: 1 1 0 0 comes out as 1 0 1 0

A complete correctness test. It confirms, for example, Batcher's 16-wire network of the next step on all 65,536 binary inputs, where 16!≈2×101316! \approx 2 \times 10^{13} permutations would be out of reach.

Check your understanding

You want to verify a candidate sorting network on 20 wires. How many inputs does the 0–1 principle require you to test?

  1. 20!≈2.4×101820! \approx 2.4 \times 10^{18}
  2. 202=40020^2 = 400
  3. 220=1,048,5762^{20} = 1{,}048{,}576
  4. (2010)=184,756\binom{20}{10} = 184{,}756
Show the answer

C. 220=1,048,5762^{20} = 1{,}048{,}576

Every 0–1 input of length 20, of which there are 2202^{20}, about a million. (The sorted ones need no test, which saves only 21.) Permutations would be over 101810^{18}.

Batcher’s bitonic and odd–even merge sorts

Batcher (1968) gave the first networks of polylogarithmic depth. Both sort the two halves recursively and in parallel, then merge them with a merging network; they differ in how they merge.

  • Bitonic sort. A bitonic sequence first rises and then falls (or is a cyclic shift of one that does). A half-cleaner compares wire ii with wire i+n/2i + n/2 for every i<n/2i < n/2. On a bitonic 0–1 input it leaves two bitonic halves, one of which is all 0s or all 1s, so every element of the first half is at most every element of the second; recursing on both halves merges in log⁡2n\log_2 n layers. To sort, sort the halves in opposite directions, which makes the whole sequence bitonic, then merge. See bitonic sort.
  • Odd–even merge sort. To merge two sorted halves, merge their even-indexed elements and their odd-indexed elements recursively, then finish with one layer of comparators between neighbors. It needs fewer comparators.
python
def oddeven_merge(lo, n, r):             # merge the two sorted halves of wires lo .. lo+n-1, stride r
    step = 2 * r
    if step < n:
        yield from oddeven_merge(lo, n, step)        # merge the even-indexed subsequence
        yield from oddeven_merge(lo + r, n, step)    # merge the odd-indexed subsequence
        for i in range(lo + r, lo + n - r, step):    # one final layer of neighbor comparators
            yield (i, i + r)
    else:
        yield (lo, lo + r)

def oddeven_merge_sort(lo, n):           # Batcher's odd-even merge sort on wires lo .. lo+n-1, n a power of 2
    if n > 1:
        m = n // 2
        yield from oddeven_merge_sort(lo, m)
        yield from oddeven_merge_sort(lo + m, m)
        yield from oddeven_merge(lo, n, 1)

print([len(list(oddeven_merge_sort(0, 2 ** k))) for k in range(1, 6)])   # [1, 5, 19, 63, 191]

The generator lists comparators as wire pairs. sorts_all_binary from the previous step confirms the 16-wire network on all 65,536 binary inputs; the bitonic version was checked the same way.

DerivationCounting comparators and layers
  1. D(2k)=D(2k−1)+k⟹D(2k)=1+2+⋯+k=k(k+1)2D(2^k) = D(2^{k-1}) + k \quad\Longrightarrow\quad D(2^k) = 1 + 2 + \dots + k = \frac{k(k+1)}{2}

    Depth. Merging two sorted halves of 2j−12^{j-1} wires takes jj layers, and the halves are sorted in parallel, so with D(2k)D(2^k) the depth on 2k2^k wires:

  2. C(2k)=2 C(2k−1)+k 2k−1⟹C(2k)=n k(k+1)4C(2^k) = 2\,C(2^{k-1}) + k\,2^{k-1} \quad\Longrightarrow\quad C(2^k) = \frac{n\,k(k+1)}{4}

    Bitonic comparators. Each of the kk layers of a bitonic merger on 2k2^k wires has 2k−12^{k-1} comparators:

  3. S(2k)=2 S(2k−1)+(k−1) 2k−1+1⟹S(2k)=(k2−k+4) 2k−2−1S(2^k) = 2\,S(2^{k-1}) + (k-1)\,2^{k-1} + 1 \quad\Longrightarrow\quad S(2^k) = (k^2 - k + 4)\,2^{k-2} - 1

    Odd–even comparators. The merge of 2k2^k wires costs M(2k)=2M(2k−1)+2k−1−1=(k−1) 2k−1+1M(2^k) = 2M(2^{k-1}) + 2^{k-1} - 1 = (k-1)\,2^{k-1} + 1, and the sort adds the two half-sorts:

nnodd–even merge sortbitonic sortdepth of bothfewest comparators known
45635
81924619
1663801060
3219124015—
All counts computed from the generators and checked against the formulas. For 8 wires, Batcher's odd–even network is optimal.
Think first Bitonic sort uses more comparators than odd–even merge sort, yet it is the favorite on GPUs and in vector code. Why?

Its structure is perfectly regular. In every layer, wire ii is compared with wire i⊕2ji \oplus 2^j for one fixed jj, so all n/2n/2 comparators of a layer perform the same operation on data at the same stride. That maps directly onto vector lanes and GPU threads, without branches or irregular indexing, while odd–even merge sort leaves some wires idle in its final layers and has a less uniform pattern.

AKS, and sorting in parallel

The construction is built from ε\varepsilon-halvers: constant-depth networks, made from expander graphs, that place all but an ε\varepsilon fraction of the smallest half of the keys on the top half of the wires. Repeated halving with careful bookkeeping of the misplaced keys sorts in O(log⁡n)O(\log n) depth. The hidden constants are enormous: even Paterson's 1990 simplification has a depth of thousands of times log⁡2n\log_2 n, and later work lowered the constant, but for any input that fits in a computer, Batcher's 12log⁡2n(log⁡2n+1)\tfrac12 \log_2 n (\log_2 n + 1) is shallower.

Networks are one model of parallel sorting. On a PRAM, where processors share memory, Cole's parallel merge sort (1988) sorts in O(log⁡n)O(\log n) time with nn processors, matching the O(nlog⁡n)O(n \log n) work of sequential sorting. Multicore and distributed systems mostly use samplesort: choose splitters from a random sample, send each key to its bucket in one pass, and sort the buckets independently. Vector and GPU code sorts small tiles with Batcher-style networks inside registers; vectorized quicksorts, for example, finish their small ranges this way (Blacher, Giesen, Sanders & Wassenberg, 2022).

Key takeaways

  • A sorting network is a fixed, data-independent sequence of comparators; its size is at least ⌈log⁡2n!⌉\lceil \log_2 n! \rceil and its depth at least ⌈log⁡2n⌉\lceil \log_2 n \rceil.
  • The 0–1 principle reduces verification to 2n2^n binary inputs, because comparators commute with nondecreasing maps.
  • Batcher's bitonic and odd–even merge sorts have depth k(k+1)/2k(k+1)/2 on 2k2^k wires and Θ(nlog⁡2n)\Theta(n \log^2 n) comparators: 80 and 63 for 16 wires.
  • Optimal sizes are known only up to 12 inputs (25, 29, 35, 39 for 9 to 12, proved by computer search), and the AKS network reaches O(log⁡n)O(\log n) depth with constants too large for practice.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A comparator network on 6 wires sorts all 64 inputs made of 0s and 1s. Does it sort every input of 6 distinct numbers?

  1. Not necessarily: it must also be tested on all 720 permutations
  2. Yes, by the 0–1 principle
  3. Only if the numbers are integers
  4. Only if its depth is at least ⌈log⁡26⌉=3\lceil \log_2 6 \rceil = 3
Show the answer

B. Yes, by the 0–1 principle

If it failed on some input xx, thresholding the values at the misplaced output would give a 0–1 input it also fails on, because comparators commute with nondecreasing maps. So the 64 binary tests are a complete proof.

Question 2

Why must every sorting network on nn wires have depth at least ⌈log⁡2n⌉\lceil \log_2 n \rceil?

  1. Because it needs at least ⌈log⁡2n!⌉\lceil \log_2 n! \rceil comparators
  2. Because after dd layers a wire's value depends on at most 2d2^d input wires, and wire 0 must be able to receive the minimum from any of the nn inputs
  3. Because each layer can contain only one comparator
  4. Because Batcher's networks have depth Θ(log⁡2n)\Theta(\log^2 n)
Show the answer

B. Because after dd layers a wire's value depends on at most 2d2^d input wires, and wire 0 must be able to receive the minimum from any of the nn inputs

Each comparator combines the information of two wires, so information spreads at most twofold per layer. Size and depth are bounded by different arguments: size by counting outcomes, depth by this fan-in argument.

Question 3

What is the depth of Batcher's odd–even merge sort, or bitonic sort, on n=2kn = 2^k wires?

  1. kk
  2. k(k+1)/2k(k+1)/2
  3. 2k−12^k - 1
  4. k2k^2
Show the answer

B. k(k+1)/2k(k+1)/2

Merging two sorted halves of size 2j−12^{j-1} takes jj layers, and the halves are sorted in parallel, so the depth is 1+2+⋯+k=k(k+1)/2=Θ(log⁡2n)1 + 2 + \dots + k = k(k+1)/2 = \Theta(\log^2 n): 10 for 16 wires.

Question 4

An adaptive comparison sort can sort 12 keys with 30 comparisons in the worst case, but the smallest sorting network for 12 inputs has 39 comparators. Why the difference?

  1. Networks compare each pair twice
  2. A network must use the same comparisons on every input, while an adaptive algorithm chooses each comparison after seeing earlier outcomes
  3. The 39-comparator network is not yet known to be optimal
  4. Networks can only compare neighboring wires
Show the answer

B. A network must use the same comparisons on every input, while an adaptive algorithm chooses each comparison after seeing earlier outcomes

Obliviousness is what makes networks parallel and data-independent, and it costs comparisons: a fixed schedule must work for every input, while a decision tree can steer its questions. Harder (2020) proved that 39 is optimal for 12 inputs.

Further reading

  • K. E. Batcher, "Sorting networks and their applications," AFIPS Spring Joint Computer Conference (1968), 307–314.
  • M. Ajtai, J. Komlós & E. Szemerédi, "An O(nlog⁡n)O(n \log n) sorting network," Proceedings of the 15th ACM Symposium on Theory of Computing (1983).
  • D. E. Knuth, The Art of Computer Programming, Vol. 3: Sorting and Searching, 2nd ed. (Addison-Wesley, 1998), §5.3.4.
  • M. Codish, L. Cruz-Filipe, M. Frank & P. Schneider-Kamp, "Twenty-five comparators is optimal when sorting nine inputs (and twenty-nine for ten)" (2014); arXiv:1405.5754.
  • J. Harder, "An answer to the Bose–Nelson sorting problem for 11 and 12 channels" (2020); arXiv:2012.04400.