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 but constants so large that Batcher's networks from 1968, of depth , 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 on size and on depth.
- State and prove the 0–1 principle, and use it to verify a network on wires with 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: sorts the two pairs; sends the overall minimum to wire 0 and the maximum to wire 3; and orders the middle two. Two lower bounds hold for every network:
Size. A network is a comparison sort whose comparisons happen not to depend on earlier outcomes, so the decision-tree bound applies:
Depth. After layers, the value on any wire depends on at most input wires, since each comparator combines two. Wire 0 must be able to receive the minimum from any of the input wires:
The simplest sorting network is odd–even transposition sort: rounds that alternately compare the pairs and It uses comparators in depth , which is wasteful, but every comparator joins neighboring wires, so it suits a line of processors that can talk only to their neighbors.
| counting bound | fewest comparators | status | |
|---|---|---|---|
| 4 | 5 | 5 | optimal |
| 8 | 16 | 19 | optimal |
| 9 | 19 | 25 | optimal: Floyd's network (1964), proved by Codish et al. (2014) |
| 10 | 22 | 29 | optimal: Waksman's network (1969), proved by Codish et al. (2014) |
| 11 | 26 | 35 | optimal, proved by Harder (2020) |
| 12 | 29 | 39 | optimal, proved by Harder (2020) |
| 16 | 45 | 60 best known | optimal size unknown |
The 0–1 principle
Checking a network on all orders is hopeless beyond tiny . 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.
Monotone maps commute with comparators. If is nondecreasing, then and likewise for max:
So they commute with networks. By induction over the comparators, running the network on yields , where is the network's output on .
Contradiction. Suppose the network fails on some : its output has for some . Take the 0–1 threshold if and 0 otherwise, which is nondecreasing. The network maps the 0–1 input to , which has before : a binary input the network fails to sort.
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 0A complete correctness test. It confirms, for example, Batcher's 16-wire network of the next step on all 65,536 binary inputs, where permutations would be out of reach.
You want to verify a candidate sorting network on 20 wires. How many inputs does the 0–1 principle require you to test?
Show the answer
C.
Every 0–1 input of length 20, of which there are , about a million. (The sorted ones need no test, which saves only 21.) Permutations would be over .
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 with wire for every . 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 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.
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.
Depth. Merging two sorted halves of wires takes layers, and the halves are sorted in parallel, so with the depth on wires:
Bitonic comparators. Each of the layers of a bitonic merger on wires has comparators:
Odd–even comparators. The merge of wires costs , and the sort adds the two half-sorts:
| odd–even merge sort | bitonic sort | depth of both | fewest comparators known | |
|---|---|---|---|---|
| 4 | 5 | 6 | 3 | 5 |
| 8 | 19 | 24 | 6 | 19 |
| 16 | 63 | 80 | 10 | 60 |
| 32 | 191 | 240 | 15 | — |
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 is compared with wire for one fixed , so all 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 -halvers: constant-depth networks, made from expander graphs, that place all but an 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 depth. The hidden constants are enormous: even Paterson's 1990 simplification has a depth of thousands of times , and later work lowered the constant, but for any input that fits in a computer, Batcher's is shallower.
Networks are one model of parallel sorting. On a PRAM, where processors share memory, Cole's parallel merge sort (1988) sorts in time with processors, matching the 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 and its depth at least .
- The 0–1 principle reduces verification to binary inputs, because comparators commute with nondecreasing maps.
- Batcher's bitonic and odd–even merge sorts have depth on wires and 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 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.
A comparator network on 6 wires sorts all 64 inputs made of 0s and 1s. Does it sort every input of 6 distinct numbers?
- Not necessarily: it must also be tested on all 720 permutations
- Yes, by the 0–1 principle
- Only if the numbers are integers
- Only if its depth is at least
Show the answer
B. Yes, by the 0–1 principle
If it failed on some input , 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.
Why must every sorting network on wires have depth at least ?
- Because it needs at least comparators
- Because after layers a wire's value depends on at most input wires, and wire 0 must be able to receive the minimum from any of the inputs
- Because each layer can contain only one comparator
- Because Batcher's networks have depth
Show the answer
B. Because after layers a wire's value depends on at most input wires, and wire 0 must be able to receive the minimum from any of the 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.
What is the depth of Batcher's odd–even merge sort, or bitonic sort, on wires?
Show the answer
B.
Merging two sorted halves of size takes layers, and the halves are sorted in parallel, so the depth is : 10 for 16 wires.
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?
- Networks compare each pair twice
- A network must use the same comparisons on every input, while an adaptive algorithm chooses each comparison after seeing earlier outcomes
- The 39-comparator network is not yet known to be optimal
- 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 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.