Bitonic Sort

Bitonic Sort is an $$O(n \log^2 n)$$ sort. it can be implemented as a sorting network, meaning it is unstable, not adaptive, and uses $$O(1)$$ memory.

Bitonic Sort is fundamentally a merge sort that uses a $$O(n \log n)$$ series of comparators to merge two sequences. Since there are $$O(\log n)$$ merge levels, Bitonic Sort has a size of $$O(n \log^2 n)$$ comparators. Each merge contains $$O(\log n)$$ layers of $$O(n)$$ comparators that can be done in parallel. Thus, a fully parallelized merge runs in $$O(\log n)$$ time therefore the algorithm runs in $$O(\log^2 n)$$ parallel time when accounting for all merge levels.

Like many merge sorting networks, Bitonic Sort also can be represented in "weaved form" where the merge merges the sorted odd and even indices instead of two contiguous sorted runs. This variant is called the Modified Bitonic Sorter or Weave Sorting Network.

The exact amount of comparators needed for Bitonic Sort if $$n$$ is a power of two:

$$\large T(n)=\frac{1 }{4 }n\left(\log_{2 }n\right)\left(\log_{2 }n+1\right)$$



Bitonic Sequence
A bitonic sequence is a sequence that is first increasing, then decreasing, or vice versa.

An example of a bitonic sequence: [2,3,4,1]

This is also a bitonic sequence: [9,8,4,2,5,6]

This is NOT a bitonic sequence: [8,6,4,5,3,2]

Note that two elements is always a bitonic sequence.

Bitonic Merging
There is a simple algorithm for turning a bitonic sequence into an increasing or decreasing sequence.

First, do a compare-and-swap for every element in the first increasing/decreasing sequence in the bitonic sequence with its corresponding element in the other sequence. this has turned one bitonic sequence into two. now, bitonic merge both of the smaller bitonic sequences.

The Sort
Bitonic sort is as follows: first, sort the first half recursively with bitonic sort in increasing order. next, sort the second half recursively in decreasing order. then, bitonic merge the bitonic sequence that was created into an increasing sequence (or decreasing if it was recursively called to sort in decreasing order).

As the comparisons never change for bitonic sort on a certain length, it can be implemented as a sorting network.

Pseudocode
Implements Recursive Bitonic Sort: procedure bitonic_sort(array arr) do recursively sort arr.start to arr.mid-1 '''ascending recursively sort arr.mid  to arr.end-1 descending bitonic_merge(arr) end procedure bitonic_merge(array arr) do if arr.length < 2 return int i = arr.start, j = arr.mid while i < arr.mid do compare and swap i and j in arr i++ j++ end while bitonic_merge(arr[arr.start : arr.mid-1]) bitonic_merge(arr[arr.mid  : arr.end-1]) end
 * 1) precondition: arr.length is a power of 2

Implementation
Implements Iterative Bitonic Sort in Java and works on lengths that are not powers of two:

Modified Bitonic Sort
(A.K.A. Weave Sorting Network)