Wiggle Sort
Given an unsorted array numsnums[0] <= nums[1] >= nums[2] <= nums[3]....
There may have multiple answers for a question, you only need to consider one of the possibilities.
Example 1
Output: [1, 6, 2, 5, 3, 4]
Explanation: This question may have multiple answers, and
[2, 6, 1, 5, 3, 4] is also okExample 2
Output: [1, 4, 2, 3]
Solution 1 - Swap elements at even and odd positions if conditions dont match
As per the problem statement, re-ordering of elements should be done in-order, i.e without using additional memory.
One way we can do that is by sorting the input array first using Arrays.sort(nums)i =1i-1
For example, consider input array as nums = [3, 5, 2, 1, 6, 4][1, 2, 3, 4, 5, 6]i-1i =1[1, 3, 2, 5, 4, 6]
Above, algoritm will take O (n log n)i =1
-
If it is an even index, we will compare with
indexed element, if the value ati+1th index is greater than value ati+1th index, then we will swap them.ith -
If it is an even index, we will compare with
indexed element, if the value ati-1th index is less than value atith index, then we will swap them.i-1th
import java.util.Arrays;
public class WiggleSort {
static void wiggleSort(int[] nums) {
if(nums.length == 1) {
return;
}
int i=1;
while(i <nums.length) {
if(i%2 == 1&& nums[i] <nums[i-1]) {
swap(nums, i, i-1);
}
if(i%2 == 0 && i+1 < nums.length && nums[i+1] > nums[i]) {
swap(nums, i, i+1);
}
i++;
}
}
static void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
public static void main(String[] args) {
int[] nums = {3, 5, 2, 1, 6, 4};
wiggleSort(nums);
System.out.println(Arrays.toString(nums));
}
}
Complexity Analysis:
Time complexity: Above code runs in O(n) time where nnums
Space complexity: O(1), since we are swapping elements in-place.
Above implementations source code can be found at