Wiggle Sort II in C++


Suppose we have an unsorted array nums, we have to rearrange it such that nums[0] < nums[1] > nums[2] < nums[3]. So if the input is like [1,5,1,1,6,4], then the output will be [1,4,1,5,1,6].

To solve this, we will follow these steps −

  • make one array x, that has same elements as nums

  • sort x array

  • i := size of x – 1, j := (size of x – 1) / 2 and n := size of nums array

  • for l in range 0 to n – 1, increase l by 2 in each step

    • nums[l] := x[j]

    • decrease j by 1

  • for l in range 1 to n – 1, increase l by 2 in each step

    • nums[l] := x[i]

    • decrease i by 1

Let us see the following implementation to get better understanding −

Example

 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) {
      vector <int> x(nums);
      sort(x.begin(), x.end());
      int i = x.size() - 1 ;
      int j = (x.size() - 1)/2;
      int n = nums.size();
      for(int l = 0; l < n; l +=2){
         nums[l] = x[j--];
      }
      for(int l = 1; l < n; l +=2){
         nums[l] = x[i--];
      }
   }
};
main(){
   vector<int> v = {1,5,1,1,6,4};
   Solution ob;
   (ob.wiggleSort(v));
   print_vector(v);
}

Input

[1,5,1,1,6,4]

Output

[1, 6, 1, 5, 1, 4, ]

Updated on: 30-Apr-2020

395 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements