Wiggle Sort

Reorder an array in place so that its values go up, down, up, down, with a single pass of swaps.

Reorder an array of integers nums in place, inside the same array, so that nums[0] <= nums[1] >= nums[2] <= nums[3] >= ...: read from left to right, the values go up, down, up, down. Equal neighbours are allowed, and any order that follows the pattern is accepted.

Example 1
Input: nums = [3, 5, 2, 1, 6, 4]
Output: [3, 5, 1, 6, 2, 4]
Explanation: [1, 6, 2, 5, 3, 4] and [2, 6, 1, 5, 3, 4] are also valid.
Example 2
Input: nums = [1, 2, 3, 4]
Output: [1, 3, 2, 4]
Solution

The Idea

Think of the teeth of a saw, or a row of hills drawn by a child: up, down, up, down. That is the shape the array must take. Read Example 1's answer, [3, 5, 1, 6, 2, 4], from the left: 3 goes up to 5, down to 1, up to 6, down to 2, and up to 4.

The input [3, 5, 2, 1, 6, 4] starts well. 3 goes up to 5 and 5 goes down to 2. Then 2 goes down to 1, where the pattern needs a step up. The easy fix would be to sort everything, but does the whole array really need to be in order?

No. Each position only has to agree with the number just before it. At an odd position (1, 3, 5) the number must be at least the one before it, a rise. At an even position (2, 4) it must be at most the one before it, a fall. So we can walk from left to right with a position i, and whenever the pair ending at i goes the wrong way, swap its two numbers. Look at the picture below.

One pass over 3, 5, 2, 1, 6, 4. At i = 3 the pair 2, 1 falls where a rise is needed, so the two numbers swap. At i = 4 the pair 2, 6 rises where a fall is needed, so they swap. The result 3, 5, 1, 6, 2, 4 goes up, down, up, down, up.

In the first row, the pairs up to position 2 are already right: 3 ≤ 5 and 5 ≥ 2. At i = 3, the pair 2, 1 falls, but position 3 needs a rise, so 2 and 1 swap. In the second row the array is [3, 5, 1, 2, 6, 4]. At i = 4, the pair 2, 6 rises where position 4 needs a fall, so they swap too. In the last row, every sign between neighbours is right.

One thing in the second row deserves a closer look. The first swap moved 1 to position 2, so it changed a pair that was already checked, 5 and the number after it. That pair is still right, because 1 is even smaller than the 2 that was there, and 5 ≥ 1 holds.

The pair staying right is not luck. A swap at a rise only happens when the number at i - 1 is the bigger one, so the swap puts a smaller number at i - 1. That number sat at the bottom of the fall before it, and a lower bottom keeps the fall a fall. A swap at a fall is the mirror image: it puts a bigger number at the top of the rise before it. So a swap never breaks a pair behind it, and one pass from left to right is enough. Fixing each problem as soon as it shows up, without ever going back, is called a greedy approach.

Solution Approach

Turning that idea into code means settling three things: whether to sort at all, how each position knows which way it should go, and what to do with equal numbers.

Sorting first

Why not just sort? Sorting does give a correct answer: sort the array, then swap the numbers at positions 1 and 2, then at 3 and 4, and so on. [1, 2, 3, 4] becomes [1, 3, 2, 4], which is Example 2's answer. But sorting takes O(n log n) time for n numbers, which for a million numbers is roughly 20 million steps. The single pass needs about a million, one per pair.

The direction at each position

How does a position know whether it needs a rise or a fall? From whether it is odd or even: i % 2 == 1 is true at odd positions, which need a rise. A pair goes the wrong way when a rise is needed but nums[i] < nums[i - 1], or when a fall is needed but nums[i] > nums[i - 1]. Position 0 has no number before it, so the walk starts at position 1.

Equal numbers

What if two neighbours are equal? The pattern uses ≤ and ≥, so equal neighbours already follow it, and nothing needs to move. That is why both checks above use a strict < or >: an equal pair never causes a swap.

A stricter version of the problem, where every rise and fall must be strict and neighbours may never be equal, is a different matter. This pass leaves equal neighbours in place, so that version needs another method.

Java Solution

The method wiggleSort works in these steps:

  1. Walk the array with one loop, moving i from position 1 to the end, since position 0 has no number before it.
  2. For each i, set shouldRise to true when i is odd, and to false when it is even.
  3. If the pair nums[i - 1], nums[i] goes the wrong way for shouldRise, swap the two numbers, using a temporary variable t to hold one of them.
  4. When the loop ends, the method returns nothing: it changed nums itself.

The main method prints each input before and after the call: the two examples, an array in falling order, two arrays with equal numbers, a single number and an empty array.

Java
import java.util.Arrays;

public class WiggleSort {

    public static void wiggleSort(int[] nums) {
        for (int i = 1; i < nums.length; i++) {
            boolean shouldRise = i % 2 == 1;   // odd positions must be >= the value before them
            if (shouldRise ? nums[i] < nums[i - 1] : nums[i] > nums[i - 1]) {
                int t = nums[i];               // wrong direction: swap the two neighbours
                nums[i] = nums[i - 1];
                nums[i - 1] = t;
            }
        }
    }

    public static void main(String[] args) {
        int[][] inputs = {
            {3, 5, 2, 1, 6, 4},
            {1, 2, 3, 4},
            {6, 5, 4, 3, 2, 1},
            {2, 2, 2},
            {1, 1, 1, 2, 2, 2},
            {7},
            {}
        };
        for (int[] nums : inputs) {
            String before = Arrays.toString(nums);
            wiggleSort(nums);
            System.out.println(before + " -> " + Arrays.toString(nums));
        }
    }
}

Running it prints:

Output
[3, 5, 2, 1, 6, 4] -> [3, 5, 1, 6, 2, 4]
[1, 2, 3, 4] -> [1, 3, 2, 4]
[6, 5, 4, 3, 2, 1] -> [5, 6, 3, 4, 1, 2]
[2, 2, 2] -> [2, 2, 2]
[1, 1, 1, 2, 2, 2] -> [1, 1, 1, 2, 2, 2]
[7] -> [7]
[] -> []

[3, 5, 1, 6, 2, 4] on the first line is the array from the last row of the picture, after the swaps at i = 3 and i = 4. In the second line, only 2 and 3 swapped, at the fall that position 2 needs.

The third line starts from [6, 5, 4, 3, 2, 1], where every pair falls. Each odd position needs a rise, so the pass swaps at positions 1, 3 and 5, and the result [5, 6, 3, 4, 1, 2] goes up and down all the way.

Look at the fifth line: [1, 1, 1, 2, 2, 2] comes back unchanged. Read with ≤ and ≥ it is valid, 1 ≤ 1 ≥ 1 ≤ 2 ≥ 2 ≤ 2, but it has equal neighbours, so it would fail the stricter version. The last two lines show that a single number or an empty array is left alone, because the loop never runs.

The original implementation, WiggleSort.java, is on GitHub.

Complexity

The work is one pass over the array, with a fixed amount of work at each position.

  • Time: O(n), for an array of n numbers, because the loop checks each of the n - 1 neighbour pairs once and does at most one swap for each.
  • Space: O(1). The numbers move inside nums, and the only extra values are i, the flag shouldRise and the swap variable t.

A related problem that also arranges numbers by comparing each one with its neighbours is Array With Elements Not Equal to Average of Neighbors.