-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwave_array.cpp
63 lines (55 loc) · 1.29 KB
/
wave_array.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution{
public:
// arr: input array
// n: size of array
//Function to sort the array into a wave-like array.
void convertToWave(vector<int>& arr, int n){
map <int,int> mp;
for(int i=0;i<n;i++)
{
mp[arr[i]]++;
}
vector <int> ans;
auto it=mp.begin();
while(it!=mp.end())
{
while(it->second>0)
{
ans.push_back(it->first);
it->second--;
}
it++;
}
for(int i=1;i<n;i+=2)
{
int temp=ans[i];
ans[i]=ans[i-1];
ans[i-1]=temp;
}
for(int i=0;i<n;i++)
{
arr[i]=ans[i];
}
}
};
// { Driver Code Starts.
int main()
{
int t,n;
cin>>t; //Input testcases
while(t--) //While testcases exist
{
cin>>n; //input size of array
vector<int> a(n); //declare vector of size n
for(int i=0;i<n;i++)
cin>>a[i]; //input elements of array
Solution ob;
ob.convertToWave(a, n);
for(int i=0;i<n;i++)
cout<<a[i]<<" "; //print array
cout<<endl;
}
} // } Driver Code Ends