Search

Search papers and lessons

Sorting Network

Level 3 · 13 min read

A sorting network sorts a fixed number of values with a fixed list of compare-and-exchange steps that never depend on the data, which makes it fast on parallel hardware.

On this page

  • Colour = topic mix
  • Discrete math
  • Algorithms
  • Calculus
  • ReadReady to readNot yet

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 kk 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 nn wires, one for each value. A comparator takes two wires, ii and jj with i<ji < j, and puts the smaller value on wire ii and the larger on wire jj. 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 3,1,4,23, 1, 4, 2.

  1. Layer 1, first pair. Compare wires 0 and 1, holding 3 and 1. The smaller goes left, so the wires now hold 1,3,4,21, 3, 4, 2. Check: wire 0 holds the smaller of the two values it compared.
  2. Layer 1, second pair. Compare wires 2 and 3, holding 4 and 2. The wires become 1,3,2,41, 3, 2, 4. Check: each pair is now in order, and the first layer's comparators did not disturb each other.
  3. 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 1,3,2,41, 3, 2, 4. Check: wire 0 now holds the smallest value, and wire 3 holds the largest.
  4. Layer 3, middle pair. Compare wires 1 and 2, holding 3 and 2. Swap them, so the wires read 1,2,3,41, 2, 3, 4. 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 i<ji < j maps the pair (ai,aj)(a_i, a_j) to (min⁡(ai,aj), max⁡(ai,aj))(\min(a_i, a_j),\ \max(a_i, a_j)). 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.

Definition: Sorting network

A sorting network on nn wires is a fixed sequence of comparators whose pairs of wires do not depend on the input. It sorts every input of nn values into non-decreasing order on the wires, from wire 00 to wire n−1n-1.

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 ff is a function that never decreases, then min⁡(f(a),f(b))=f(min⁡(a,b))\min(f(a), f(b)) = f(\min(a, b)) and the same holds for max⁡\max. 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 n=4n = 4 this means checking 24=162^4 = 16 inputs, not 4!4! orderings of arbitrary numbers.

Check the four-wire network with the 0-1 input 1,0,1,01, 0, 1, 0. Layer 1 compares (1,0)(1, 0) and gives 0,10, 1, then (1,0)(1, 0) gives 0,10, 1, so the wires read 0,1,0,10, 1, 0, 1. Layer 2 compares wires 0 and 2, which hold 00 and 00, and wires 1 and 3, which hold 11 and 11, so nothing moves. Layer 3 compares wires 1 and 2, holding 11 and 00, and swaps them to give 0,0,1,10, 0, 1, 1. Sorted.

Step 2 in symbols: the cost of the bitonic network

Let n=2kn = 2^k. The bitonic network has k(k+1)/2k(k+1)/2 stages, and each stage has n/2n/2 comparators, because each comparator uses two of the nn wires and every wire is used once per stage. So the size is

size=n2⋅k(k+1)2=n k(k+1)4.\text{size} = \frac{n}{2} \cdot \frac{k(k+1)}{2} = \frac{n\,k(k+1)}{4}.

For n=8n = 8 with k=3k = 3 this is 8×3×44=24\frac{8 \times 3 \times 4}{4} = 24, which matches the stage count above. The depth is k(k+1)/2k(k+1)/2, one layer per stage, so it grows like the square of the logarithm of nn.

Step 3 in symbols: why comparisons are not the whole story

A comparison sort on nn values needs at least log⁡2(n!)\log_2(n!) comparisons in the worst case, which grows like nlog⁡2nn \log_2 n (see Sorting Algorithm). The bitonic network uses about n4log⁡22n\frac{n}{4} \log_2^2 n comparators, so it does more work than the best sequential algorithms, by a factor that grows with log⁡2n\log_2 n. 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

Example
1. Two values (tiny)

Sort the pair 5,25, 2 on two wires.

  1. The only comparator is on wires 0 and 1. It holds 5 and 2.
  2. The smaller value goes to wire 0, so the wires read 2,52, 5.
  3. Check: 2≤52 \le 5, 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.

Example
2. Four values with the five-comparator network (standard)

Use the network from "How it works" on the values 8,6,7,58, 6, 7, 5.

  1. Layer 1, compare wires 0 and 1 (8 and 6): swap, so the wires read 6,8,7,56, 8, 7, 5.
  2. Layer 1, compare wires 2 and 3 (7 and 5): swap, so the wires read 6,8,5,76, 8, 5, 7.
  3. Layer 2, compare wires 0 and 2 (6 and 5): swap, so the wires read 5,8,6,75, 8, 6, 7.
  4. Layer 2, compare wires 1 and 3 (8 and 7): swap, so the wires read 5,7,6,85, 7, 6, 8.
  5. Layer 3, compare wires 1 and 2 (7 and 6): swap, so the wires read 5,6,7,85, 6, 7, 8.
  6. 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.

Example
3. Eight values on SIMD lanes (realistic)

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.

  1. Insertion sort, worst case: 8×72=28\frac{8 \times 7}{2} = 28 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.
  2. Bitonic network for n=8n = 8: 24 comparators in 6 stages. With 4 comparators per stage running in parallel on the vector unit, the work is 6 parallel steps.
  3. 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.
  4. Check: 24/4=624 / 4 = 6, 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: k=4k = 4, so there are 4×52=10\frac{4 \times 5}{2} = 10 stages, each with 16/2=816 / 2 = 8 comparators. Total: 10×8=8010 \times 8 = 80 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 log⁡2n\log_2 n, but they finish in a number of layers that grows only like log⁡2n\log^2 n, 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 O(log⁡n)O(\log n), 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 2k2^k values with k(k+1)/2k(k+1)/2 stages and n k(k+1)4\frac{n\,k(k+1)}{4} 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
Only its position in the fixed list of comparators. The pairs of wires are the same for every input, so the network does not look at the values to choose what to compare next.
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
Layer 1: (0,1) gives 2, 4, 3, 1; (2,3) gives 2, 4, 1, 3. Layer 2: (0,2) holds 2 and 1, so the wires become 1, 4, 2, 3; (1,3) holds 4 and 3, so they become 1, 3, 2, 4. Layer 3: (1,2) holds 3 and 2, so they become 1, 2, 3, 4. The output is sorted.
QuestionWhy is a bitonic network with more comparators than a sequential sort still a good choice on a GPU?Show answer
Its steps are fixed and branch-free, and each stage has many comparators that can run at the same time. The depth grows like log⁡2n\log^2 n, so the number of layers that must run one after another is small. A sequential sort has fewer comparisons but long chains of data-dependent steps that do not use parallel lanes well.
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
Padding from 100 to 128 values adds 28 dummy values, so the network does the work for 128 values, about 28 percent more than needed. Before choosing it, you would check whether the per-thread work fits in registers, whether the fixed comparator count beats a partial selection method, and whether the top 10 can be kept in a small sorted queue instead of sorting everything. The answer depends on the hardware and on how much the branch-free layout saves.

Sources