Wiggle Sort in Java
Learn how Wiggle 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.
Introduction
Wiggle Sort doesn’t put an array in ascending order. It arranges the values so that they go up and down in turn:
\[a_0 < a_1 > a_2 < a_3 > a_4 < \dots\]Every value at an odd index is a peak, larger than both neighbours, and every value at an even index is a valley. There are usually many valid answers; any one of them will do.
Three ideas carry the whole algorithm:
- Split at the median: if the values larger than the median fill the odd indexes and the values smaller than it fill the even indexes, every peak is larger than its neighbours.
- Find the median in linear time: QuickSelect finds it without sorting the array.
- Partition on virtual indexes: a three-way partition, like the Dutch National Flag Sort, puts the larger values first, the copies of the median in the middle, and the smaller values last, but on a remapped order of the indexes that visits all the odd indexes before the even ones.
The hard part is duplicates. The strict “<” and “>” mean that two equal values may never be neighbours, so the copies of the median have to be kept apart, and some arrays can’t be wiggled at all: 1, 2, 2 has no valid arrangement.
This article uses the strict wiggle sort with a median and virtual indexing, the version from the repository’s WiggleSort class. The repository also has a WaveSort class, which solves the easier, non-strict version in a single pass; it is described at the end of the Java code.
Performance Characteristics
Wiggle Sort makes a constant number of linear passes: one QuickSelect, one count, and one partition.
Time Complexity
Time complexity describes how the number of steps an algorithm takes grows as the input gets larger.
| Case | Time | When it happens |
|---|---|---|
| Best | $O(n)$ | Any input: the median search, the count and the partition are all linear |
| Average | $O(n)$ | Random input: about 11.6 comparisons per value for a million values |
| Worst | $O(n)$ | QuickSelect picks its pivots by “median of medians”, so no input forces $O(n^2)$ |
Why linear? A plain QuickSelect can be unlucky with its pivots, like Quicksort, and take $O(n^2)$ time. The repository’s QuickSelect chooses each pivot with the median of medians method: it takes the median of every group of five values, then the median of those medians. That pivot is never too far from the middle, so each round throws away a fixed fraction of the values and the total work stays linear. The partition then looks at every value once, with one or two comparisons each.
With the repository code, the number of comparisons per value grew only slowly, from 6.6 for 10 values to 11.6 for a million, and a million random values took about 0.1 seconds. A million values that were already sorted took about 0.04 seconds.
Space Complexity
Space complexity describes how much extra memory an algorithm needs, beyond the input itself, as the input gets larger.
| Property | Value |
|---|---|
| Space | $O(\log n)$: QuickSelect’s recursion when it picks a pivot |
| In place | Yes |
| Stable | No (the result isn’t sorted, so the order of equal values isn’t kept) |
Algorithm (Pseudo Code)
Wiggle Sort first finds the median: the value that would be at index $\lfloor n/2 \rfloor$ if the array were sorted. It counts how often the median occurs. If it occurs more than $\lceil n/2 \rceil$ times, no wiggle exists, because two copies would have to be neighbours. For an odd length, it may occur exactly $\lceil n/2 \rceil$ times only if it is also the smallest value: then the copies fill all the even indexes, the valleys.
Then comes a three-way partition around the median. Instead of indexes 0, 1, 2, …, it walks virtual indexes, each mapped to a real index:
\[\text{mapIndex}(v) = (2v + 1) \bmod (n \mid 1)\]Here $n \mid 1$ is $n$ rounded up to an odd number. For 10 values, virtual indexes 0 to 9 map to the real indexes 1, 3, 5, 7, 9, 0, 2, 4, 6, 8: first all the odd indexes, then all the even ones.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
sort(array):
median = QuickSelect(array, n / 2)
numMedians = number of values equal to median
if n is odd and numMedians == ceil(n / 2) and median isn't the smallest value: fail
if numMedians > ceil(n / 2): fail
i = 0, j = 0, k = n - 1 (virtual indexes)
while j <= k:
x = array[mapIndex(j)]
if x > median: swap(mapIndex(j), mapIndex(i)); i++; j++
if x < median: swap(mapIndex(j), mapIndex(k)); k--
if x == median: j++
return array
mapIndex(v) = (2v + 1) % (n | 1)
After the partition, the larger values sit at the first virtual indexes, which are the odd real indexes from left to right. The smaller values sit at the last virtual indexes, the even real indexes from right to left. The copies of the median fill the gap in between: the last odd indexes and the first even indexes, at opposite ends of the array. So a peak is always a larger value or a median, a valley is always a smaller value or a median, and two medians never meet.
Why not just sort the array and put the larger half at the odd indexes? You can, in $O(n \log n)$ time, but both halves have to be placed in reverse order, or the medians can end up as neighbours: for 4, 5, 5, 6, the naive interleave gives 4 < 5 > 5 < 6, which breaks at 5 > 5, while the reversed halves give 5 < 6 > 4 < 5. The virtual indexes do the same job in linear time and without extra space.
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 virtual index of every slot, the pointers of the partition, 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.
- Virtual indexes: during the partition, the small labels under the cells show each slot’s virtual index, v0 to v9.
- Pointers: i is the next slot for a larger value, j is the value being checked, and k is the next slot for a smaller value. They all move through virtual indexes, so they jump around the real array.
- Colours: the copies of the median are outlined and turn amber while they are counted, swapped values are salmon, and values in their final group are green. In the last step, the peaks are raised.
- Duplicates: tick Duplicates to use values between 0 and 3 with repeats, and see how the copies of the median are kept apart.
- Counters: the footer shows the median, the comparisons in the partition, and the swap calls (a swap of a slot with itself changes nothing).
Java Code
The implementation is a WiggleSort class with one public method, sort, and three private methods: wiggleSort finds and checks the median, triColorSort partitions, and mapIndex computes the virtual indexes. It uses QuickSelect, Ceil and Floor from the repository’s utility package, and swap from SortUtils. The repository notes that these classes were taken from TheAlgorithms/Java.
The complete code is in the algorithm-examples repository on GitHub:
WiggleSort.java, with the helpers inQuickSelect.javaandSortUtils.java.
sort
1
2
3
4
@Override
public <T extends Comparable<T>> T[] sort(T[] unsorted) {
return wiggleSort(unsorted);
}
sort accepts an array of any Comparable type and hands it to wiggleSort, which rearranges it in place and returns it.
wiggleSort
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
private <T extends Comparable<T>> T[] wiggleSort(T[] sortThis) {
T median;
median = select(Arrays.asList(sortThis), (int) floor(sortThis.length / 2.0));
int numMedians = 0;
for (T sortThi : sortThis) {
if (0 == sortThi.compareTo(median)) {
numMedians++;
}
}
if (sortThis.length % 2 == 1 && numMedians == ceil(sortThis.length / 2.0)) {
T smallestValue = select(Arrays.asList(sortThis), 0);
if (!(0 == smallestValue.compareTo(median))) {
throw new IllegalArgumentException("For odd Arrays if the median appears ceil(n/2) times, "
+ "the median has to be the smallest values in the array.");
}
}
if (numMedians > ceil(sortThis.length / 2.0)) {
throw new IllegalArgumentException("No more than half the number of values may be the same.");
}
triColorSort(sortThis, median);
return sortThis;
}
wiggleSort finds the median with select, counts its copies, and checks the two conditions from the pseudo code before partitioning. Arrays.asList doesn’t copy the array: it wraps it in a list that writes through to it, so QuickSelect reorders the array itself while it searches. That is harmless, because the partition rearranges everything anyway.
The two checks are exact. A test of every array of up to 7 values from 0 to 3, 21,844 arrays in all, found that the code throws precisely when no wiggle exists, and otherwise always returns a valid one.
A few details are worth noticing:
- The checks only look at the median, but that is enough: a value that occurs more than half the time always includes the middle position of the sorted order, so it is the median.
- For the odd-length check, the code runs QuickSelect a second time, with index 0, only to find the smallest value. A simple loop over the array would do the same.
floor(sortThis.length / 2.0)andceil(sortThis.length / 2.0)use the repository’s ownFloorandCeilclasses, which work ondouble. Integer arithmetic,length / 2and(length + 1) / 2, gives the same results.
Not every array can be wiggled, and this method says so with an
IllegalArgumentException: for 1, 2, 2, or whenever more than half the values are equal. An empty array throws anIllegalArgumentExceptiontoo, from QuickSelect (“The list of elements must not be empty.”), although an empty array is trivially wiggled. Every other sort in the repository simply returns it.
triColorSort
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private <T extends Comparable<T>> void triColorSort(T[] sortThis, T median) {
int n = sortThis.length;
int i = 0;
int j = 0;
int k = n - 1;
while (j <= k) {
if (0 < sortThis[mapIndex(j, n)].compareTo(median)) {
SortUtils.swap(sortThis, mapIndex(j, n), mapIndex(i, n));
i++;
j++;
} else if (0 > sortThis[mapIndex(j, n)].compareTo(median)) {
SortUtils.swap(sortThis, mapIndex(j, n), mapIndex(k, n));
k--;
} else {
j++;
}
}
}
triColorSort is the Dutch National Flag partition, with every index passed through mapIndex. A value larger than the median swaps to virtual index i, and both i and j move on: the value that comes back is a copy of the median, which has already been checked. A value smaller than the median swaps to virtual index k, and only k moves, because the value that comes back hasn’t been checked yet. A copy of the median stays where it is. Each value costs one comparison if it is larger than the median, and two otherwise.
mapIndex
1
2
3
private int mapIndex(int index, int n) {
return ((2 * index + 1) % (n | 1));
}
mapIndex turns a virtual index into a real one. n | 1 sets the lowest bit, which makes an even n odd and leaves an odd n alone. For 10 values it is 11, and the virtual indexes 0 to 9 map to 1, 3, 5, 7, 9, 0, 2, 4, 6, 8. For 9 values it is 9, and they map to 1, 3, 5, 7, 0, 2, 4, 6, 8. In both cases, the odd indexes come first.
select and swap
select is the repository’s QuickSelect. It returns the value that would be at index n if the list were sorted, using the median of medians to choose its pivots, and throws an exception for an empty list. Its comment calls this “the n-th largest element”, but it is the n-th smallest: index 0 gives the minimum, which is how wiggleSort uses it.
In QuickSelect’s
partition5, the group fromlefttorightis sorted withlist.subList(left, right), which excludesright, so the last value of every group of five is left out of the sort. The method still returns a value from the group, and the results are correct, but the pivot isn’t always the true median of five. In the tests above, the work still grew linearly, for random and for sorted input.
swap from SortUtils exchanges two elements, and does nothing when both indexes are the same.
Running it
1
2
3
4
Integer[] numbers = {7, 2, 9, 4, 0, 8, 3, 6, 1, 5};
new WiggleSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 8, 2, 6, 3, 7, 1, 9, 4, 5]
Create a WiggleSort, pass it an array, and the same array comes back wiggled: 0 < 8 > 2 < 6 > 3 < 7 > 1 < 9 > 4 < 5. It takes 60 comparisons, counting QuickSelect, the count of medians and the partition. The array holds Integer, not int, because the method works with Comparable objects.
WaveSort: the relaxed version
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;
}
The repository’s WaveSort solves the non-strict version, $a_0 \ge a_1 \le a_2 \ge a_3 \le \dots$, with the peaks at the even indexes. It needs no median: it visits every even index and swaps with a smaller neighbour on either side. A swap with the right neighbour only makes the value at i larger, so it stays at least as large as its left neighbour, and one pass is enough, in $O(n)$ time and $O(1)$ space, and it never fails, because equal neighbours are allowed. For the example array it returns 7, 2, 9, 0, 8, 3, 6, 1, 5, 4. The class also has an isWaveSorted method to check a result. The Wave Sort guide walks through it step by step.
Summary
- Wiggle Sort arranges an array so that it goes up and down in turn: $a_0 < a_1 > a_2 < \dots$ It does not sort the array.
- It finds the median with QuickSelect, puts the larger values at the odd indexes and the smaller values at the even indexes, and keeps the copies of the median apart with virtual indexes.
- It runs in $O(n)$ time with $O(\log n)$ extra space, and rearranges the array in place.
- Some arrays have no strict wiggle; the repository code detects exactly those and throws an
IllegalArgumentException, and it throws one for an empty array as well. - When equal neighbours are allowed, the repository’s
WaveSortdoes the job in a single pass: see Wave Sort.
