# 280. Wiggle Sort

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]
``````

``````class Solution {
public:
void wiggleSort(vector<int>& nums) {
sort(nums.begin(), nums.end());
if (nums.size() <= 2) return;
for (int i = 2; i < nums.size(); i += 2) {
swap(nums[i], nums[i - 1]);
}
}
};
``````

``````class Solution {
public:
void wiggleSort(vector<int>& nums) {
if (nums.size() <= 1) return;
for (int i = 1; i < nums.size(); ++i) {
if ((i % 2 == 1 && nums[i] < nums[i - 1]) || (i % 2 == 0 && nums[i] > nums[i - 1])) {
swap(nums[i], nums[i - 1]);
}
}
}
};
``````

Github 同步地址：

https://github.com/grandyang/leetcode/issues/280

Wiggle Sort II

Sort Colors

https://leetcode.com/problems/wiggle-sort/

https://leetcode.com/problems/wiggle-sort/discuss/71692/Java-O(N)-solution

https://leetcode.com/problems/wiggle-sort/discuss/71688/4-lines-O(n)-C%2B%2B

https://leetcode.com/problems/wiggle-sort/discuss/71693/My-explanations-of-the-best-voted-Algo

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation