Wiggle Sort

Description

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

For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4].

Hint

Train of Thought

Code

public class Solution {
    public void wiggleSort(int[] nums) {
        if (nums == null || nums.length == 0) {
            return;
        }

        for (int i = 1; i < nums.length; i++) {
            //if i is odd, it must greater than two sides 
            if (i % 2 == 1) {
                if (nums[i] < nums[i - 1]) {
                    swap(nums, i - 1, i);
                }
            }
            // if it is even, it must smaller than i -1 
            if (i % 2 == 0) {
                if (nums[i] > nums[i - 1]) {
                    swap(nums, i - 1, i);
                }
            }
        }

    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

Complexity

results matching ""

    No results matching ""