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;
}

2 thoughts on “LeetCode – Wiggle Sort (Java)”

  1. [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

Leave a Comment