Post

Wave Sort in Java

Learn how Wave 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.

Wave Sort in Java

Introduction

Wave Sort doesn’t put an array in ascending order. It arranges the values so that they go down and up in turn, like a wave:

\[a_0 \ge a_1 \le a_2 \ge a_3 \le a_4 \ge \dots\]

Every value at an even index is a peak, at least as large as its neighbours, and every value at an odd index is a valley. Equal neighbours are allowed, so every array has a wave arrangement, and usually many.

Two ideas carry the whole algorithm:

  • Only visit the peaks: the loop steps through the even indexes, 0, 2, 4, …, and leaves the odd indexes to be fixed by their neighbours.
  • Look left, then right: if the value at an even index is smaller than its left neighbour, swap them; then, if it is smaller than its right neighbour, swap them too. After that, it is a peak.

Wave Sort is the relaxed sibling of Wiggle Sort. Wiggle Sort asks for strict inequalities, $a_0 < a_1 > a_2 < \dots$, which forces it to find the median and keep equal values apart, and some arrays have no answer at all. Wave Sort allows equal neighbours, so a single pass of neighbour swaps is enough, and it never fails.

A wave is useful when you need alternating highs and lows but not a full order, and it is a common interview question: the obvious answer is to sort the array and swap neighbouring pairs, in $O(n \log n)$ time; the better answer is this linear pass.

Performance Characteristics

Wave Sort compares every pair of neighbours exactly once, so its work doesn’t depend on the input at all; only the number of swaps does.

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 array that already is a wave: $n - 1$ comparisons and no swaps
Average$O(n)$Random input: $n - 1$ comparisons and some swaps
Worst$O(n)$Any input: never more than $n - 1$ comparisons and $n - 1$ swaps

Why $n - 1$? Each even index is compared with its left neighbour (if it has one) and its right neighbour (if it has one). Every pair of neighbours contains exactly one even index, so every pair is compared exactly once. With the repository code, 10 values always take 9 comparisons, and 10 million random values took about 0.04 seconds.

Even an array in ascending order needs work: 0, 1, 2, …, 9 becomes 1, 0, 3, 2, 5, 4, 7, 6, 9, 8, with one swap for every pair. An array in descending order already starts with a peak, but it still needs swaps further on.

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 loop index and a temporary value for the swap
In placeYes
StableYes: only unequal neighbours are swapped, so equal values keep their order

Algorithm (Pseudo Code)

Wave Sort visits the even indexes from left to right. At each one, it first looks left: if the value is smaller than its left neighbour, the two swap. Then it looks right: if the value is smaller than its right neighbour, those two swap. The value at the even index is now at least as large as both neighbours.

1
2
3
4
5
6
7
sort(array):
    for i = 0, 2, 4, ... while i < n:
        if i > 0 and array[i] < array[i - 1]:
            swap(i, i - 1)
        if i < n - 1 and array[i] < array[i + 1]:
            swap(i, i + 1)
    return array

Why doesn’t a later swap break an earlier peak? Two facts keep everything in place:

  • The left swap keeps the valley a valley. When array[i] is smaller than array[i - 1], it moves to index i - 1. It is smaller than the old value there, which was already no larger than the peak at i - 2, so index i - 1 is still a valley.
  • The right swap only raises the peak. When array[i] is smaller than array[i + 1], the larger value moves to index i, so index i is still at least as large as its left neighbour.

After index i is handled, nothing touches indexes 0 to i again, so they are final.

The left check matters. For 5, 4, 3, index 0 is already a peak, but at index 2 the 3 is smaller than its left neighbour 4. The left swap gives 5, 3, 4, which is a wave. Without it, the loop would stop at 5, 4, 3, where the last value isn’t a peak.

Visualization

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

Each step shows the array, the even index being handled, 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.
  • Pointer: i is the even index being made into a peak.
  • Colours: the two neighbours being compared are amber, swapped values are salmon, and values in their final place are green. Final peaks are raised, so the wave grows from left to right.
  • Duplicates: tick Duplicates to use values between 0 and 3 with repeats. The small number in each cell is its original position, so you can see that equal values keep their order.
  • Counters: the footer counts the comparisons and swaps.
compared swapped final (peaks raised) i = even index

Java Code

The implementation is a WaveSort class with two public methods: sort, which arranges the array, and isWaveSorted, which checks a result. Two small helpers, swap and less, live in a separate SortUtils class. The repository notes that the class was taken from TheAlgorithms/Java.

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

sort

1
2
3
4
5
6
7
8
9
10
11
12
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
    for (int i = 0; i < array.length; i += 2) {
        if (i > 0 && SortUtils.less(array[i], array[i - 1])) {
            SortUtils.swap(array, i, i - 1);
        }
        if (i < array.length - 1 && SortUtils.less(array[i], array[i + 1])) {
            SortUtils.swap(array, i, i + 1);
        }
    }
    return array;
}

sort accepts an array of any Comparable type and rearranges it in place. The loop steps by 2, so i is always even. The i > 0 test skips the left check at index 0, and the i < array.length - 1 test skips the right check when the array has an odd length and i is the last index. Empty and one-element arrays come back unchanged.

The comparisons use less, a strict “smaller than”, so equal neighbours are never swapped. That is what makes the sort stable, and it is also why the result can have equal neighbours: 2, 2, 2, 2 is already a valid wave.

isWaveSorted

1
2
3
4
5
6
7
8
9
10
11
public <T extends Comparable<T>> boolean isWaveSorted(T[] array) {
    for (int i = 0; i < array.length; i += 2) {
        if (i > 0 && SortUtils.less(array[i], array[i - 1])) {
            return false;
        }
        if (i < array.length - 1 && SortUtils.less(array[i], array[i + 1])) {
            return false;
        }
    }
    return true;
}

isWaveSorted makes the same checks as sort, but returns false instead of swapping. It is handy in tests: a test of every array of up to 8 values from 0 to 3, 87,381 arrays in all, found that sort always produces a result that isWaveSorted accepts.

Both methods’ comments describe the result as “every alternate element is greater than its adjacent elements”, but the code allows equal neighbours: a peak only has to be at least as large. And the peaks are at the even indexes. isWaveSorted returns false for 1, 3, 2, which is a perfect wiggle, because its peak is at index 1.

swap and less

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 less(T firstElement, T secondElement) {
    return firstElement.compareTo(secondElement) < 0;
}

These helpers from SortUtils keep the code easy to read. swap exchanges two elements, and less returns true when the first element is smaller than the second, using 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};
new WaveSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [7, 2, 9, 0, 8, 3, 6, 1, 5, 4]

Create a WaveSort, pass it an array, and the same array comes back as a wave: 7 ≥ 2 ≤ 9 ≥ 0 ≤ 8 ≥ 3 ≤ 6 ≥ 1 ≤ 5 ≥ 4. It takes 9 comparisons and 6 swaps. The array holds Integer, not int, because the method works with Comparable objects.

Summary

  • Wave Sort arranges an array so that it goes down and up in turn: $a_0 \ge a_1 \le a_2 \ge \dots$ It does not sort the array.
  • It visits the even indexes and swaps with a smaller neighbour on the left, then on the right, which makes each even index a peak without breaking the earlier ones.
  • It makes exactly $n - 1$ comparisons, runs in $O(n)$ time with $O(1)$ extra space, and is in place and stable.
  • It never fails, because equal neighbours are allowed. When they aren’t, use Wiggle Sort, which needs the median and can’t wiggle every array.
This post is licensed under CC BY 4.0 by the author.