Wiggle Sort
280.Wiggle Sort
Array
Greedy
Bit Manipulation
Problem Statement:
Given an unsorted array nums, reorder it in-place such that nums[0] ≤ nums[1] ≥ nums[2] ≤ nums[3].... The final array should satisfy the wiggle property where every odd index is greater than or equal to its adjacent elements.
Example:
Input:
nums = [3,5,2,1,6,4]→
Output:
[3,5,1,6,2,4]Algorithm:
- Traverse array checking adjacent elements
- Even indices should be less than next
- Odd indices should be greater than next
- Swap if condition not met
Complexity:
Time: O(n) | Space: O(1)
Java Solution:
public void wiggleSort(int[] nums) {
for (int i = 0; i < nums.length - 1; i++) {
if (((i % 2 == 0) && nums[i] > nums[i + 1]) // Even index should be less than next
|| ((i % 2 == 1) && nums[i] < nums[i + 1])) { // Odd index should be greater than next
swap(nums, i, i + 1);
}
}
}
public void swap(int[] nums, int i, int j) {
nums[i] ^= nums[j];
nums[j] ^= nums[i];
nums[i] ^= nums[j];
}
Python Solution:
def wiggleSort(self, nums: List[int]) -> None:
for i in range(len(nums) - 1):
if ((i % 2 == 0 and nums[i] > nums[i + 1]) or
(i % 2 == 1 and nums[i] < nums[i + 1])):
nums[i], nums[i + 1] = nums[i + 1], nums[i] # Python swap
C++ Solution:
class Solution {
public:
void wiggleSort(vector<int>& nums) {
for (int i = 0; i < nums.size() - 1; i++) {
if ((i % 2 == 0 && nums[i] > nums[i + 1]) ||
(i % 2 == 1 && nums[i] < nums[i + 1])) {
swap(nums[i], nums[i + 1]); // C++ built-in swap
}
}
}
};