> For the complete documentation index, see [llms.txt](https://jimmylin1991.gitbook.io/practice-of-algorithm-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jimmylin1991.gitbook.io/practice-of-algorithm-problems/array/280.-wiggle-sort.md).

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

{% hint style="info" %}
i代表在nums中的index，如果i是偶數，nums\[i] <= nums\[i - 1]，如果i是奇數，nums\[i] >= nums\[i - 1]。如果不符合這兩個規則，那就要調換數字。
{% endhint %}

```cpp
void wiggleSort(vector<int>& nums) { // time: O(n); space: O(1)
    for (int i = 1; i < nums.size(); ++i) {
        if (i & 1) {
            if (nums[i] < nums[i - 1]) swap(nums[i], nums[i - 1]);
        } else {
            if (nums[i] > nums[i - 1]) swap(nums[i], nums[i - 1]);
        }
    }
}
```
