Algorithm Visualiser by Tsvetozar Biserov

Bitonic Sort

  • Ω( n log2 n )
  • Θ( n log2 n )
  • O( n log2 n )
  • space O( log n )

Bitonic sort decides in advance which pairs of positions to compare, whatever the values are. It builds a bitonic sequence, one that falls and then rises, by sorting one half downward and the other upward, then straightens it with rounds of compare-exchanges at halving distances. Because the pattern depends only on the array length, it is a sorting network, and this version also accepts lengths that are not powers of two.

Array
Comparator strip Index down, time to the right
100 elements
×20 steps/frame

Comparisons 1
—
Reads 2
—
Writes 2
—
Swaps 3
—
Real time 4
—
Visual time 4
—
  1. Comparisons count only element-against-element checks; loop and index checks are never counted.
  2. Reads and writes include reads and writes to helper buffers (merge, counting, radix, bucket and tim sort).
  3. A swap counts once, as a swap. It is never also counted as a read or a write.
  4. Real time is the average time of the counted sort on this device over repeated runs, measured once before playback and independent of animation speed. Visual time is the time spent animating, excluding pauses.

How bitonic sort works

For six elements the sort splits into three and three. The first half is sorted descending, the second ascending. In the first half, positions 1 and 2 hold 2 and 6, and descending order wants the larger one first, so they swap: 5, 6, 2, 1, 4, 3. The merge of those three elements then compares positions 0 and 2 (5 and 2, already in order) and finally positions 0 and 1, where 5 and 6 swap, giving 6, 5, 2, 1, 4, 3.

In the second half the 4 and the 3 swap into ascending order, 6, 5, 2, 1, 3, 4, and the 1 is already below both, so nothing else moves. The whole array now falls to the 1 and then rises, which is the bitonic shape. The final merge begins by comparing each position with the one four places further on: 6 and 3 swap, then 5 and 4 swap, giving 3, 4, 2, 1, 6, 5. The four smallest values now occupy the first four slots and the two largest the last two.

The two parts are finished independently. The front four are compared at distance 2, where 3 and 2 swap and then 4 and 1 swap, giving 2, 1, 3, 4, 6, 5, and then at distance 1, where 2 and 1 swap. The last two get one swap of 6 and 5. That makes 9 swaps and exactly 13 comparisons. Any other arrangement of the six values would trigger the same 13 comparisons but possibly a different number of swaps.

Bitonic Sort on 5 2 6 1 4 3, one swap or write at a time. Indexes count from 0.
Step Change Array after
1 Swap indexes 1 and 2 5 6 2 1 4 3
2 Swap indexes 0 and 1 6 5 2 1 4 3
3 Swap indexes 4 and 5 6 5 2 1 3 4
4 Swap indexes 0 and 4 3 5 2 1 6 4
5 Swap indexes 1 and 5 3 4 2 1 6 5
6 Swap indexes 0 and 2 2 4 3 1 6 5
7 Swap indexes 1 and 3 2 1 3 4 6 5
8 Swap indexes 0 and 1 1 2 3 4 6 5
9 Swap indexes 4 and 5 1 2 3 4 5 6

All 9 changes are shown.

Pseudocode

sort(lo, n, ascending)
  if n <= 1
    return
  m = floor(n / 2)
  sort(lo, m, not ascending)
  sort(lo + m, n - m, ascending)
  merge(lo, n, ascending)

merge(lo, n, ascending)
  if n <= 1
    return
  m = largest power of two below n
  for i = lo to lo + n - m - 1
    compare a[i], a[i + m] and swap if out of order for the direction
  merge(lo, m, ascending)
  merge(lo + m, n - m, ascending)

Why these complexities

For a power-of-two length n, the sort has log₂ n merge stages, and the stage that produces runs of length 2ᵏ takes k rounds of compare-exchanges, each over n/2 pairs. Adding the rounds 1 + 2 + ... + log₂ n gives n log₂ n (log₂ n + 1) / 4 comparisons, which is O(n log² n). That is more than merge sort or heap sort need, and the extra log factor is what you pay for a fixed schedule.

Best, average and worst are the same because nothing in the comparison pattern reads the data. The code walks the same index pairs for every input, so six elements always cost 13 comparisons, sorted or not. Only the swap count varies. Even a sorted array is not left alone, since the first half is deliberately sorted downward before the merge flips it back. That is the opposite of an adaptive algorithm such as insertion sort.

The payoff is parallelism. All compare-exchanges in one round touch disjoint pairs, so n/2 of them can run at the same moment, and the whole network is only log₂ n (log₂ n + 1) / 2 rounds deep. This sequential version cannot use that, but it needs only the recursion stack, about log n frames, so space is O(log n) and the sort works in place. It is not stable, because an exchange across a distance can carry an element past an equal one.

Measured on this site

Exact counts from this site's own engine for 32 elements, using the same rules as the visualiser.

Input Comparisons Writes Swaps
Random 240 0 119
Already sorted 240 0 112
Reversed 240 0 128
Few distinct values 240 0 71

When to use it

Use it on parallel hardware such as GPUs, where its fixed pattern of compare-exchanges maps well to many threads. Run sequentially, as here, there are faster choices.

Frequently asked questions

What is a sorting network?

A fixed sequence of compare-and-swap operations that sorts every input. The operations never depend on the data.

Why is the comparison count O(n log² n)?

There are about log n merge stages, and the stage that builds sequences of length 2^k takes k compare-exchange rounds of n/2 comparisons each.

Does it need a power-of-two size?

The classic network does. This version also handles other sizes.

How does this version handle six elements, which is not a power of two?

The merge splits a segment at the largest power of two below its length. For six elements it first pairs position i with i + 4, but only for i = 0 and 1, because the others would fall off the end. Comparisons that would reach past the end are simply not made, and the recursion then handles a block of four and a block of two separately.

Why does the first half get sorted downward?

A bitonic merge needs input that first falls and then rises, or the reverse. Sorting the first half descending and the second ascending produces exactly that shape. The direction flag is passed down the recursion and is flipped for the first half at every split, so each smaller merge ends up with the orientation it needs. With two ascending runs, the same merge would not straighten the sequence.

Background

Ken Batcher described both the bitonic sorter and the odd-even merge sorter in his 1968 paper Sorting Networks and Their Applications. His interest was in hardware: comparators wired in a fixed pattern that sort at the speed of the circuitry, with no branching on the data. Knuth gives sorting networks their own section, 5.3.4, and the 0-1 principle used there is the standard tool for proving them correct: a comparator network that sorts every sequence of zeros and ones sorts every input.

The bitonic merge is short to write and maps directly onto GPU threads, one thread per compare-exchange, which is why graphics-oriented sorting code has used it for decades. Networks with better depth exist, such as the AKS network of 1983 with O(log n) depth, but its constants are so large that Batcher's 1968 constructions are still the practical choice.

References

  • Batcher, Sorting Networks and Their Applications, AFIPS Spring Joint Computer Conference, 1968
  • Knuth, The Art of Computer Programming, vol. 3, section 5.3.4 (Networks for Sorting)
  • Cormen, Leiserson, Rivest, Stein, Introduction to Algorithms, 2nd edition, chapter 27 (Sorting Networks)

Compare with

Algorithm Average time Worst time
Merge Sort Θ( n log n ) O( n log n )
Big O notation
Best time Ω( n log2 n ) fair
Average time Θ( n log2 n ) fair
Worst time O( n log2 n ) fair
Worst space O( log n ) good

Properties

Stable
No
In place
Yes
Adaptive
No
Comparison-based
Yes