-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rearrange_Array_Alternately.cpp
64 lines (51 loc) · 1.13 KB
/
Rearrange_Array_Alternately.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
64
// C++ program to rearrange an array in minimum
// maximum form
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// arr: input array
// n: size of array
void rearrange(long long *arr, int n)
{
int l = 0, r = n - 1, MAX = arr[n-1] + 1;
bool idx = 1;
for (int i = 0; i < n; ++i){
if(idx){
arr[i] += (arr[r] % MAX)*MAX*1LL;
r--;
idx = 0;
}else{
arr[i] += (arr[l] % MAX)*MAX*1LL;
l++;
idx = 1;
}
}
for (int i = 0; i < n; ++i)
arr[i] /= MAX;
}
// { Driver Code Starts.
// Driver program to test above function
int main()
{
int t;
//testcases
cin >> t;
while(t--){
//size of array
int n;
cin >> n;
long long arr[n];
//adding elements to the array
for(int i = 0;i<n;i++){
cin >> arr[i];
}
//calling rearrange() function
rearrange(arr, n);
//printing the elements
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
return 0;
}
// } Driver Code Ends