-
Notifications
You must be signed in to change notification settings - Fork 22
/
array in zig-zag fashion
46 lines (39 loc) · 1.15 KB
/
array in zig-zag fashion
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
/*
Given an array A (distinct elements) of size N. Rearrange the elements of array in zig-zag fashion. The converted array should be in form a
< b > c < d > e < f. The relative order of elements is same in the output i.e you have to iterate on the original array only.
Input:
The first line of input contains an integer T denoting the number of test cases. T testcases follow. Each testcase contains two lines of
input. The first line contains a single integer N denoting the size of array.
The second line contains N space-separated integers denoting the elements of the array.
Output:
For each testcase, print the array in Zig-Zag fashion.
Constraints:
1 <= T <= 100
1 <= N <= 100
0 <= Ai <= 10000
Example:
Input:
2
7
4 3 7 8 6 2 1
4
1 4 3 2
Output:
3 7 4 8 2 6 1
1 4 2 3
*/
#include <bits/stdc++.h>
using namespace std;
int main() {
int t; cin>>t; while(t--){
int n; cin>>n;
int a[n]; for(int i=0; i<n; i++) cin>>a[i];
for(int i=0; i<n; i+=2){
if(i+1<n && a[i+1] < a[i]) swap(a[i+1] , a[i]);
if(i+2<n && a[i+1] < a[i+2]) swap(a[i+1], a[i+2]);
}
for(int i=0; i<n; i++) cout<<a[i]<<" ";
cout<<'\n';
}
return 0;
}