Wiggle Sort in C++


Suppose we have an unsorted array called nums, we have to reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3].... and so on.

So, if the input is like nums = [3,5,2,1,6,4], then the output will be [3,5,1,6,2,4], there may be some other answers.

To solve this, we will follow these steps −

  • n := size of nums

  • for initialize i := 0, when i < n - 1, update i := i + 1, do −

    • if i is even and nums[i] > nums[i+1] is true or i is odd and nums[i] > nums[i+1] is false, then

      • swap(nums[i], nums[i + 1])

Example 

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto< v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   void wiggleSort(vector<int<& nums) {
      int n = nums.size();
      for(int i = 0; i < n - 1; i+=1){
         if((i % 2 == 0) == ( nums[i] > nums[i + 1])){
            swap(nums[i], nums[i + 1]);
         }
      }
   }
};
main(){
   vector<int< v = {3,5,2,1,6,4};
   Solution ob;
   ob.wiggleSort(v);
   print_vector(v);
}

Input

{3,5,2,1,6,4}

Output

[3, 5, 1, 6, 2, 4, ]

Updated on: 18-Nov-2020

790 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements