Post

Odd-Even Sort in Java

Learn how Odd-Even 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.

Odd-Even Sort in Java

Introduction

Odd-Even Sort, also called brick sort or odd-even transposition sort, is a comparison sort related to bubble sort. Like bubble sort, it only compares and swaps neighbours. The difference is the order: instead of walking along the array, it compares all neighbour pairs that start at an odd index in one phase, and all pairs that start at an even index in the next.

Three ideas carry the whole algorithm:

  • Odd phase: compare the pairs (1, 2), (3, 4), (5, 6), … and swap any pair that is out of order.
  • Even phase: compare the pairs (0, 1), (2, 3), (4, 5), … the same way. Drawn under the array, the two phases’ pairs overlap like the bricks of a wall.
  • Independent pairs: within one phase, no two pairs share a value, so all their comparisons could happen at the same time.

Odd-Even Sort was designed for parallel processors connected in a line, where each processor holds one value and can only talk to its neighbours. With one processor per value, every phase takes a single step, and the whole array is sorted after at most $n$ phases. On a single processor it is no faster than bubble sort, but it is a classic example of how an algorithm’s shape decides how well it runs in parallel, much like Bitonic Sort.

This article uses Odd-Even Sort with a sorted flag: rounds of an odd phase followed by an even phase repeat until a round makes no swaps.

Performance Characteristics

Odd-Even Sort only ever swaps neighbours, so like bubble sort its work depends on how far the values are from their places; the difference is how much of that work can run in parallel.

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)$An already sorted array: the first round makes no swaps, and the sort ends
Average$O(n^2)$Random input
Worst$O(n^2)$Reverse-sorted input: the values at the ends have to cross the whole array

Why $n^2$? Each round makes about $n$ comparisons, and a value can move at most one position per phase, so a value at the wrong end of the array needs about $n$ phases to reach its place. That is $O(n)$ rounds of $O(n)$ comparisons. With $n / 2$ processors, though, each phase takes constant time, so the parallel running time is only $O(n)$.

A well-known result guarantees that $n$ phases are always enough to sort $n$ values. A parallel implementation can therefore skip the sorted flag and simply run $n$ phases, which avoids having all processors agree on whether anything was swapped.

Space Complexity

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

PropertyValue
Space$O(1)$: a flag and a loop index
In placeYes
StableYes (equal neighbours are never swapped)

Algorithm (Pseudo Code)

Odd-Even Sort runs in rounds. A round starts with the odd phase: the value at index 1 is compared with index 2, index 3 with index 4, and so on, and every pair whose left value is greater is swapped. Then the even phase does the same with the pairs starting at index 0, 2, 4, and so on. Between them, the two phases compare every pair of neighbours once.

The rounds repeat. A large value can move one place right in every phase, and a small value one place left, so values drift towards their places a step at a time, from both directions at once. When a whole round makes no swaps, every pair of neighbours is in order, and the array is sorted.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
sort(array):
    sorted = false
    while not sorted:
        sorted = performOddSort(array)
        sorted = performEvenSort(array) and sorted

performOddSort(array):
    sorted = true
    for i = 1, 3, 5, … while i < n - 1:
        if array[i] > array[i + 1]: swap(i, i + 1), sorted = false
    return sorted

performEvenSort(array):
    sorted = true
    for i = 0, 2, 4, … while i < n - 1:
        if array[i] > array[i + 1]: swap(i, i + 1), sorted = false
    return sorted

After a round in which neither phase swaps, every value is less than or equal to its right neighbour, so the array is sorted.

The order of the operands in performEvenSort(array) && sorted matters. Java’s && stops as soon as the left side is false, so with sorted && performEvenSort(array), the even phase would be skipped whenever the odd phase swapped. Calling the method first makes sure both phases run in every round.

Visualization

The visualization below follows the Java code phase by phase, starting with the values 0 to 9 in shuffled order.

Each step shows one whole phase, because all of its comparisons are independent: the pairs it compared, marked with brackets under the array, which of them were swapped, and the line of code that ran, with a short explanation of what 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.
  • Pairs: the brackets under the array join the pairs of the current phase. Values that are not part of any pair in this phase fade out; in the odd phase that is the first value, and with an even length also the last.
  • Colours: pairs that were already in order are amber, pairs that were swapped are salmon, and the array turns green when it is sorted.
  • Phase: the footer shows the phase, the round, and the number of comparisons so far.
compared, in order compared, swapped sorted

Java Code

The implementation is an OddEvenSort class with one public method, sort, and two private methods: performOddSort runs the odd phase and performEvenSort runs the even phase. Each returns true when it made no swaps. Two small helpers, swap and greater, live in a separate SortUtils class.

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

sort

1
2
3
4
5
6
7
8
9
10
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
    boolean sorted = false;
    while (!sorted) {
        sorted = performOddSort(array);
        sorted = performEvenSort(array) && sorted;
    }

    return array;
}

sort is the entry point. It accepts an array of any Comparable type and repeats rounds until a round makes no swaps. Each round runs the odd phase, then the even phase, and sorted is only true when both report that nothing moved. The array is sorted in place and returned. Empty and one-element arrays need no special case: both phases have nothing to compare, return true, and the loop ends after one round.

performOddSort

1
2
3
4
5
6
7
8
9
10
private <T extends Comparable<T>> boolean performOddSort(T[] array) {
    boolean sorted = true;
    for (int i = 1; i < array.length - 1; i += 2) {
        if (SortUtils.greater(array[i], array[i + 1])) {
            SortUtils.swap(array, i, i + 1);
            sorted = false;
        }
    }
    return sorted;
}

performOddSort compares the pairs that start at an odd index: (1, 2), (3, 4), and so on, as long as a right neighbour exists. i moves two places at a time, so the pairs never overlap. When the left value is greater, the pair is swapped and sorted becomes false.

performEvenSort

1
2
3
4
5
6
7
8
9
10
private <T extends Comparable<T>> boolean performEvenSort(T[] array) {
    boolean sorted = true;
    for (int i = 0; i < array.length - 1; i += 2) {
        if (SortUtils.greater(array[i], array[i + 1])) {
            SortUtils.swap(array, i, i + 1);
            sorted = false;
        }
    }
    return sorted;
}

performEvenSort is the same loop starting at index 0, so it compares (0, 1), (2, 3), and so on. The two methods differ only in their starting index; a single method with the start as a parameter would remove the duplication.

swap and greater

1
2
3
4
5
6
7
8
9
10
11
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 greater(T firstElement, T secondElement) {
    return firstElement.compareTo(secondElement) > 0;
}

These helpers from SortUtils keep the phases easy to read. swap exchanges two elements, and greater returns true when the first element is larger than the second, using compareTo. Because greater is strict, equal neighbours are never swapped, which makes the sort stable.

Running it

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

Create an OddEvenSort, pass it an array, and the same array comes back sorted, after five rounds: four that sort and a last one that confirms nothing moves. The array holds Integer, not int, because the method works with Comparable objects.

Summary

  • Odd-Even Sort is a neighbour-swapping sort, like bubble sort, that alternates an odd phase and an even phase of non-overlapping pairs.
  • This implementation repeats rounds of both phases until a round makes no swaps; performEvenSort(array) && sorted makes sure both phases always run.
  • After a round without swaps, every value is less than or equal to its right neighbour, so the array is sorted.
  • It runs in $O(n)$ on sorted input and $O(n^2)$ otherwise on one processor, but only $O(n)$ parallel time with one processor per pair, needs $O(1)$ extra space, and is stable and in place.
  • Use it on parallel hardware where processors can only talk to their neighbours. On a single core, prefer insertion sort for small arrays, or an $O(n \log n)$ sort such as Arrays.sort().
This post is licensed under CC BY 4.0 by the author.