-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRearrange Array Alternately.cpp
77 lines (61 loc) · 1.48 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
65
66
67
68
69
70
71
72
73
74
75
76
77
// { Driver Code Starts
// C++ program to rearrange an array in minimum
// maximum form
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution{
public:
// This function wants you to modify the given input
// array and no need to return anything
// arr: input array
// n: size of array
//Function to rearrange the array elements alternately.
void rearrange(long long *A, int n)
{
//int * a = new int[n];
int j=0 , k = n-1, max_ele = A[n-1] +1 ;
for(int i =0 ; i < n ;i ++)
{
if( i %2 == 0 )
{
A[i] += (A[k] % max_ele ) * max_ele;
k --;
}
else
{
A[i] += ( A[j] % max_ele) * max_ele;
j++;
}
}
for(int i =0 ; i < n ;i ++)
A[i] /= max_ele;
}
};
// { 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];
}
Solution ob;
//calling rearrange() function
ob.rearrange(arr, n);
//printing the elements
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
return 0;
}
// } Driver Code Ends