Post

Bitonic Sort in Java

Learn how Bitonic Sort works: its time and space complexity, the algorithm in pseudo code, and a step-by-step visualisation that follows the Java code line by line.

Bitonic Sort in Java

Introduction

Bitonic Sort is a divide-and-conquer comparison sort designed for parallel hardware. It builds bitonic sequences, which first rise and then fall, and merges them with a fixed pattern of compare-and-swap steps. The pattern of comparisons never depends on the values, which is what makes it easy to run in parallel.

Three ideas carry the whole algorithm:

  • Bitonic sequence: a sequence that first increases and then decreases, such as [1, 4, 7, 9, 6, 3]. Sorting the first half upwards and the second half downwards creates one.
  • Bitonic merge: comparing each value in the first half with the value at the same position in the second half, and swapping where needed, splits a bitonic sequence into two smaller bitonic sequences, with every value of one smaller than every value of the other. Repeating that on both halves sorts it.
  • Sorting network: because the same pairs are compared whatever the input, the whole sort is a fixed network of comparators. All comparisons in one stage are independent and can run at the same time.

Ken Batcher published Bitonic Sort in 1968, together with odd-even merge sort, as a way to build sorting hardware. It makes more comparisons than merge sort, but its fixed, regular pattern maps perfectly onto GPUs, SIMD instructions and hardware circuits, where thousands of comparisons happen at once. GPU sorting libraries and FPGA designs still use it today.

This article uses recursive Bitonic Sort with padding: the array is copied into an array whose length is a power of two, the extra slots are filled with the largest value, and the sorted copy is cut back to the original length.

Performance Characteristics

Bitonic Sort makes exactly the same comparisons for every input of a given size, so its time depends only on the length of the padded array.

Time Complexity

Time complexity describes how the number of steps an algorithm takes grows as the input gets larger.

CaseTimeWhen it happens
Best$O(n \log^2 n)$Any input: the network compares the same pairs every time
Average$O(n \log^2 n)$Any input
Worst$O(n \log^2 n)$Any input; padding can almost double $n$ when the length is just above a power of two

Why $n \log^2 n$? Merging a bitonic sequence of length $m$ takes $\log_2 m$ rounds of $m / 2$ comparisons. Sorting builds sorted runs of length 2, 4, 8, …, $n$, and each level merges the whole array once, so the total is $\frac{n}{2} \cdot \frac{\log_2 n (\log_2 n + 1)}{2}$ comparisons. For the 16 slots of the visualization that is exactly 80. On a parallel machine with $n / 2$ processors, each round takes one step, so the sort finishes in $O(\log^2 n)$ time.

On a single CPU core, Bitonic Sort is slower than merge sort or QuickSort, because of the extra $\log n$ factor and the padding. It pays off when many comparators can work at once, such as on a GPU.

Space Complexity

Space complexity describes how much extra memory an algorithm needs, beyond the input itself, as the input gets larger.

PropertyValue
Space$O(n)$ for the padded copy and the result, plus $O(\log n)$ for the recursion
In placeNo (this implementation sorts a padded copy and returns a new array)
StableNo (values are swapped across long distances, regardless of equal values in between)

Algorithm (Pseudo Code)

Bitonic Sort splits the range in half, sorts the first half in ascending order and the second half in descending order, the same way, recursively. Together, the two halves now form a bitonic sequence: up, then down. A single value counts as sorted, so the recursion stops there.

Then the bitonic sequence is merged. Each value in the first half is compared with the value exactly half the length further on, and the pair is swapped if it is in the wrong order for the requested direction. After that, every value in one half is smaller than every value in the other, and both halves are bitonic again, so the same merge repeats on each half, until the halves are single values and the whole range is sorted.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
sort(array):
    paddedSize = nextPowerOfTwo(n)
    paddedArray = copy of array, filled up to paddedSize with max(array)
    bitonicSort(paddedArray, 0, paddedSize, ASCENDING)
    return first n values of paddedArray

bitonicSort(array, low, cnt, direction):
    if cnt > 1:
        k = cnt / 2
        bitonicSort(array, low, k, ASCENDING)
        bitonicSort(array, low + k, cnt - k, DESCENDING)
        bitonicMerge(array, low, cnt, direction)

bitonicMerge(array, low, cnt, direction):
    if cnt > 1:
        k = cnt / 2
        for i = low to low + k - 1:
            if array[i], array[i + k] are not in direction order: swap them
        bitonicMerge(array, low, k, direction)
        bitonicMerge(array, low + k, cnt - k, direction)

After bitonicMerge(array, low, cnt, direction), the range array[low .. low + cnt - 1] is sorted in the given direction.

The split only works when every half has exactly the same length, which is why the length must be a power of two. The padding values are copies of the largest value, so in an ascending sort they all collect at the right end, past the original values, where they are cut off.

Visualization

The visualization below follows the Java code line by line, starting with the values 0 to 9 in shuffled order, padded to 16 slots.

Each step shows one call of bitonicMerge: the range it works on, the pairs it compares, joined by arcs, and the line of code that is running, with a short explanation of what just happened:

  • Step through: use the arrows to move one step forward or back, or drag the slider to jump to any step.
  • Play: press Play to run the steps automatically, and press it again to pause.
  • Shuffle: press the shuffle button to start again with a new random order.
  • Padding: the six dashed cells on the right are the padding, copies of the largest value.
  • Range and pairs: cells outside the range of the current merge fade out. Each arc joins two values that are compared; the pairs in one step are independent and could all be compared at the same time.
  • Colours: compared pairs that were already in order are amber, pairs that were swapped are salmon, and the array turns green when it is sorted.
  • Direction: the footer shows whether the current merge sorts its range ascending (↑) or descending (↓), and counts the comparisons.
compared, in order compared, swapped sorted padding

Java Code

The implementation is a BitonicSort class with one public method, sort, and four private methods: bitonicSort builds the bitonic sequences recursively, bitonicMerge merges them, nextPowerOfTwo works out the padded length, and max finds the padding value. A private enum, Direction, holds ASCENDING and DESCENDING. Three small helpers, swap, less and greater, live in a separate SortUtils class.

The complete code is in the algorithm-examples repository on GitHub: BitonicSort.java, with the helpers in SortUtils.java.

sort

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
    if (array == null) {
        throw new IllegalArgumentException("The input array cannot be null");
    }
    if (array.length == 0) {
        return array;
    }

    final int paddedSize = nextPowerOfTwo(array.length);
    T[] paddedArray = Arrays.copyOf(array, paddedSize);

    final T maxValue = max(array);
    Arrays.fill(paddedArray, array.length, paddedSize, maxValue);

    bitonicSort(paddedArray, 0, paddedSize, Direction.ASCENDING);
    return Arrays.copyOf(paddedArray, array.length);
}

sort is the entry point. It rejects null with an IllegalArgumentException, returns an empty array straight back, and otherwise copies the array into one whose length is the next power of two. The extra slots get the largest value, so they sort to the end. After sorting the padded copy in ascending order, sort returns its first array.length values as a new array.

sort never changes the array it is given, not even when its length is already a power of two, because it always sorts a copy. Calling new BitonicSort().sort(numbers) and then printing numbers shows the original order; only the returned array is sorted. Every other SortAlgorithm in the repository sorts the array in place, so code that ignores the return value works with them, but not with this one.

bitonicSort

1
2
3
4
5
6
7
8
9
10
11
private <T extends Comparable<T>> void bitonicSort(final T[] array, final int low, final int cnt, final Direction direction) {
    if (cnt > 1) {
        final int k = cnt / 2;

        bitonicSort(array, low, k, Direction.ASCENDING);

        bitonicSort(array, low + k, cnt - k, Direction.DESCENDING);

        bitonicMerge(array, low, cnt, direction);
    }
}

bitonicSort sorts cnt values starting at low in the given direction. It sorts the first half ascending and the second half descending, which turns the range into a bitonic sequence, and then merges it in the requested direction. The recursion bottoms out at single values. The source comment above the merge says “in ascending order”, but the merge uses direction, which is descending for every second half one level up.

bitonicMerge

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private <T extends Comparable<T>> void bitonicMerge(T[] array, int low, int cnt, Direction direction) {
    if (cnt > 1) {
        final int k = cnt / 2;

        final BiPredicate<T, T> areSorted = (direction == Direction.ASCENDING) ? (a, b) -> SortUtils.less(a, b) : (a, b) -> SortUtils.greater(a, b);
        for (int i = low; i < low + k; i++) {
            if (!areSorted.test(array[i], array[i + k])) {
                SortUtils.swap(array, i, i + k);
            }
        }

        bitonicMerge(array, low, k, direction);
        bitonicMerge(array, low + k, cnt - k, direction);
    }
}

bitonicMerge turns a bitonic range into a sorted one. areSorted is less for an ascending merge and greater for a descending one. The loop compares every value in the first half with the value k positions later and swaps them when they are not in order. That leaves two bitonic halves, every value of one on the correct side of every value of the other, and the method merges each half the same way.

Two details are worth noticing:

  • The comparisons in the loop are independent of each other: no pair shares a value with another pair. On parallel hardware, all k of them can run at the same moment.
  • areSorted uses a strict comparison, so a pair of equal values counts as “not sorted” and is swapped. That does no harm to the result, but it costs a write.

nextPowerOfTwo and max

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private static int nextPowerOfTwo(int n) {
    int count = 0;

    if ((n & (n - 1)) == 0) {
        return n;
    }

    while (n != 0) {
        n >>= 1;
        count += 1;
    }

    return 1 << count;
}

private static <T extends Comparable<T>> T max(final T[] array) {
    return Arrays.stream(array).max(Comparable::compareTo).orElseThrow();
}

nextPowerOfTwo returns n itself when it is already a power of two: then n & (n - 1) clears its only set bit and gives 0. Otherwise it counts how many bits n has, by shifting it right until it is 0, and returns 2 to that power; for 10, which has 4 bits, that is 16. max finds the largest value with a stream, to use as padding.

swap, less and greater

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static <T> void swap(T[] array, int i, int j) {
    if (i != j) {
        final T temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

public static <T extends Comparable<T>> boolean less(T firstElement, T secondElement) {
    return firstElement.compareTo(secondElement) < 0;
}

public static <T extends Comparable<T>> boolean greater(T firstElement, T secondElement) {
    return firstElement.compareTo(secondElement) > 0;
}

These helpers from SortUtils keep bitonicMerge easy to read. swap exchanges two elements, and less and greater compare two elements with compareTo, so the algorithm works for any type that implements Comparable.

Running it

1
2
3
4
Integer[] numbers = {7, 2, 9, 4, 0, 8, 3, 6, 1, 5};
Integer[] sorted = new BitonicSort().sort(numbers);
System.out.println(Arrays.toString(sorted));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Create a BitonicSort, pass it an array, and keep the array it returns: numbers itself is unchanged. The ten values are padded to 16 internally, sorted with 80 comparisons, and cut back to ten.

Summary

  • Bitonic Sort is a parallel-friendly divide-and-conquer sort: it builds bitonic sequences (up, then down) and merges them with a fixed network of compare-and-swap steps.
  • This implementation pads the array to a power of two with its largest value, sorts the halves in opposite directions, and merges recursively.
  • After each bitonicMerge, its range is sorted in the requested direction, and the final merge sorts the whole padded array.
  • It always makes $O(n \log^2 n)$ comparisons, needs $O(n)$ extra space for the padded copy, and is not stable and not in place.
  • On one CPU core, merge sort, QuickSort or Arrays.sort() are faster. Bitonic Sort is the right choice on GPUs and other hardware that can compare many pairs at once.
This post is licensed under CC BY 4.0 by the author.