LeetCode – Wiggle Sort (Java)

Given an unsorted array nums, reorder it in-place such that nums[0] < nums[1] > nums[2] < nums[3].... Example:

Input: nums = [3,5,2,1,6,4]
Output: One possible answer is [3,5,1,6,2,4]

Java Solution

public void wiggleSort(int[] nums) {
    if (nums == null || nums.length <= 1) {
        return;
    }
 
    for (int i = 1; i < nums.length; i++) {
        if (i % 2 == 1) {
            if (nums[i - 1] > nums[i]) {
                swap(nums, i - 1, i);
            }
        } else {
            if (nums[i - 1] < nums[i]) {
                swap(nums, i - 1, i);
            }
        }
    }
}
 
private void swap(int[] nums, int i, int j) {
    int t = nums[i];
    nums[i] = nums[j];
    nums[j] = t;
}
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Ritesh Kumar

    [1,2,1,2,1,2,1,1,1,2,2,2] this case also does not worker.
    Please dont visit this blog its a waste of time

  • Shawn Li

    [2,5,2,2,1,4] doesn’t work