TL;DR
A sorting network is a fixed recipe for putting a set of values in order. The recipe is a list of compare-and-exchange steps on fixed pairs of positions, and the pairs are the same whatever the numbers are. Each step puts the smaller value on the left and the larger on the right. Because nothing is decided by the data, the steps can run side by side on parallel hardware, and the bitonic network is the classic way to build one for any power-of-two size.
Builds on: Sorting Algorithm, Big-O Notation · Leads to: FAISS's in-register top-k selection
Where it's used
Small sorts inside a GPU kernel. The FAISS paper (2017) needs the smallest of many distances for each query. It keeps the small sorted queues in the registers of one GPU warp of 32 lanes, and sorts them with a bitonic-style network and odd-size merging networks, because each lane can follow the same fixed steps with no branches. See Billion-scale similarity search with GPUs.
Hardware sorters and SIMD code. A circuit that sorts a few fixed-width values, or a vector instruction that sorts the lanes of a register, is naturally a network: every comparator is a small piece of wiring that always does the same work. Sorting libraries for SIMD CPUs use the same idea to sort short runs of numbers without any if statements.
Priority queues and merging in parallel systems. Networks can merge two sorted lists of fixed length in a few parallel rounds, which is useful when a fixed amount of hardware must handle many merges at once.
How it works
A sorting network has wires, one for each value. A comparator takes two wires, and with , and puts the smaller value on wire and the larger on wire . The network is a list of comparators, grouped into layers. Comparators in the same layer touch different wires, so they can run at the same time.
The smallest interesting network has four wires and five comparators, in three layers. Here is the network on the values .
- Layer 1, first pair. Compare wires 0 and 1, holding 3 and 1. The smaller goes left, so the wires now hold . Check: wire 0 holds the smaller of the two values it compared.
- Layer 1, second pair. Compare wires 2 and 3, holding 4 and 2. The wires become . Check: each pair is now in order, and the first layer's comparators did not disturb each other.
- Layer 2, outer pair. Compare wires 0 and 2, holding 1 and 2. They are already in order, so nothing moves. Compare wires 1 and 3, holding 3 and 4. Also in order. The wires still read . Check: wire 0 now holds the smallest value, and wire 3 holds the largest.
- Layer 3, middle pair. Compare wires 1 and 2, holding 3 and 2. Swap them, so the wires read . Check: the list is sorted.
The whole network used five comparators and three layers, and it made three swaps. The same five comparators would sort any four values, including ones that are already in order, because the steps never look at the values to decide what to do next.
flowchart LR
subgraph L1[Layer 1]
a1["compare 0 and 1"]
a2["compare 2 and 3"]
end
subgraph L2[Layer 2]
b1["compare 0 and 2"]
b2["compare 1 and 3"]
end
subgraph L3[Layer 3]
c1["compare 1 and 2"]
end
L1 --> L2 --> L3
Bitonic sorting uses the same comparators to sort any list whose length is a power of two. It works in two phases: first it builds a bitonic sequence (one that rises then falls), then it splits and merges that sequence until it is sorted. The network has a regular pattern, so it can be written as a loop. For eight values it has six stages with four comparators in each, 24 comparators in all.
The math
A comparator on wires maps the pair to . A network is a sequence of comparators. Its size is the total number of comparators. Its depth is the number of layers when comparators that share no wire are grouped together, because those are the steps that can run in parallel.
A sorting network on wires is a fixed sequence of comparators whose pairs of wires do not depend on the input. It sorts every input of values into non-decreasing order on the wires, from wire to wire .
Because the wire pairs are fixed, a network is a finite circuit. The question of whether it works is therefore a finite check, and one fact makes that check small.
The zero-one principle
If a network sorts every input made only of 0s and 1s, it sorts every input. The reason is that a comparator commutes with any increasing function: if is a function that never decreases, then and the same holds for . Replace each value by 1 when it is at least a threshold and by 0 otherwise. The 0-1 image of the network's output is the network's output on the 0-1 image of the input, and a 0-1 list is sorted exactly when no 1 sits before a 0. For this means checking inputs, not orderings of arbitrary numbers.
Check the four-wire network with the 0-1 input . Layer 1 compares and gives , then gives , so the wires read . Layer 2 compares wires 0 and 2, which hold and , and wires 1 and 3, which hold and , so nothing moves. Layer 3 compares wires 1 and 2, holding and , and swaps them to give . Sorted.
Step 2 in symbols: the cost of the bitonic network
Let . The bitonic network has stages, and each stage has comparators, because each comparator uses two of the wires and every wire is used once per stage. So the size is
For with this is , which matches the stage count above. The depth is , one layer per stage, so it grows like the square of the logarithm of .
Step 3 in symbols: why comparisons are not the whole story
A comparison sort on values needs at least comparisons in the worst case, which grows like (see Sorting Algorithm). The bitonic network uses about comparators, so it does more work than the best sequential algorithms, by a factor that grows with . What it gains is depth: a few layers that run in parallel, instead of a long chain of data-dependent steps. That is the trade made by sorting networks. They are more work and more predictable, and that is why they win on parallel hardware.
Worked examples
Sort the pair on two wires.
- The only comparator is on wires 0 and 1. It holds 5 and 2.
- The smaller value goes to wire 0, so the wires read .
- Check: , so the output is sorted.
Interpretation: a single comparator is a sorting network for two values. It is the basic step that every larger network repeats.
Use the network from "How it works" on the values .
- Layer 1, compare wires 0 and 1 (8 and 6): swap, so the wires read .
- Layer 1, compare wires 2 and 3 (7 and 5): swap, so the wires read .
- Layer 2, compare wires 0 and 2 (6 and 5): swap, so the wires read .
- Layer 2, compare wires 1 and 3 (8 and 7): swap, so the wires read .
- Layer 3, compare wires 1 and 2 (7 and 6): swap, so the wires read .
- Count the swaps: all five comparators swapped. Total: 5 comparators, 5 swaps, depth 3.
Interpretation: the network moved the global minimum to wire 0 and the global maximum to wire 3 in its first two layers, and the last comparator fixed the middle two. A selection-based method would have needed to search for each place, but here each place was settled by a single fixed step.
A vector unit sorts 8 values held in one register, with 4 comparators running at once in each step. Compare two ways to sort them.
- Insertion sort, worst case: comparisons. Each one depends on the result of the one before, and each is a branch that may or may not move data, so the lanes must wait on the branch.
- Bitonic network for : 24 comparators in 6 stages. With 4 comparators per stage running in parallel on the vector unit, the work is 6 parallel steps.
- Both methods sort 8 values. Here the network's 24 comparators are fewer than the insertion sort's worst case of 28. The difference that matters is shape: the network's steps are fixed and branch-free and finish in 6 parallel steps, while the insertion sort is a chain of up to 28 dependent comparisons on a sequential machine.
- Check: , which matches the number of stages.
Interpretation: on hardware that rewards predictable parallel work, the network wins on depth and on the absence of branches. Comparison count alone would not show this. On large inputs the bitonic network does more total work than the best sequential sorts, so it pays for its parallel shape with extra comparisons.
Try it: a bitonic network on 16 values. How many stages and how many comparators does it have? Work it out before reading on.
Answer: , so there are stages, each with comparators. Total: comparators.
Common mistakes and tradeoffs
It is tempting to think a sorting network is a sorting algorithm with a fixed number of steps that happen to be data-dependent. In fact the wire pairs never change, and nothing in the network reads the values to decide what to do next. That is the whole point: a network is a circuit, not a program with branches.
It is tempting to think a network is a Compare-and-Swap instruction on shared memory. In fact a comparator in a network is an ordinary operation on values in local positions. It needs no atomicity because no other Thread can touch those wires during the step. The name is similar, but the two ideas solve different problems.
It is tempting to think that fewer comparators always means faster. In fact the parallel depth matters as much as the total work. Bitonic networks do more comparators than the best sequential sort, a gap that grows with , but they finish in a number of layers that grows only like , and each layer can run at once.
It is tempting to think a network can sort any number of values. In fact a network is built for one fixed size, and it is usually built for a power of two. To sort fewer values, the common trick is to pad with values that sort to the end, such as the largest possible number. That padding costs comparators.
When to use one: a small, fixed number of values, a parallel or hardware setting, and inner loops that must have no branches. When not to use one: large lists on a general-purpose sequential machine, or inputs of many different sizes, where recursive merge sort or quicksort does less total work and handles any size. Insertion sort is a fine choice for a handful of values on a sequential machine.
History
Ken Batcher described sorting networks and the bitonic and odd-even merge networks in 1968. A network with four wires and five comparators was known to be the smallest possible for four values, and Donald Knuth discussed sorting networks at length in The Art of Computer Programming, Volume 3, in 1973.
In 1983 Ajtai, Komlós and Szemerédi gave a network of depth , which is the best possible depth, but its constant factors are so large that it is not used in practice. Batcher's bitonic network remained the practical choice because its regular structure maps well onto hardware and parallel machines. Modern GPU and SIMD sorters, including the in-register selection in the FAISS paper, return to the same idea: fixed steps that never branch.
Recap
- A sorting network is a fixed list of compare-and-exchange steps on fixed pairs of wires.
- A comparator puts the smaller value on the lower wire, and comparators in one layer can run in parallel.
- The zero-one principle lets you check a network on 0-1 inputs only, which is a finite and small test.
- The bitonic network sorts values with stages and comparators.
- The network does more total work than a good sequential sort, but its parallel depth and lack of branches make it fast on parallel hardware, which is why FAISS uses one for its in-register top-k.
What to read next: Billion-scale similarity search with GPUs shows the network inside a GPU search kernel, and Sorting Algorithm gives the sequential methods that networks are compared against.
Check yourself
QuestionIn a sorting network, what decides which two wires a comparator uses?Show answer
QuestionA four-wire network has comparators on (0,1), (2,3), (0,2), (1,3) and (1,2), in that order with the first two in the same layer. The input is 4, 2, 3, 1. What are the wires after all five comparators?Show answer
QuestionWhy is a bitonic network with more comparators than a sequential sort still a good choice on a GPU?Show answer
QuestionApplied: you need the 10 smallest of 100 values on each of thousands of GPU threads, and you are considering a bitonic network that pads the input to 128 values. What costs does the padding add, and what would you check before choosing it?Show answer
Sources
- Sorting network (Wikipedia)
- Johnson, Douze and Jégou, Billion-scale similarity search with GPUs, arXiv:1702.08734: arxiv.org/abs/1702.08734