-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathreverse array by groups.cpp
59 lines (50 loc) · 1.12 KB
/
reverse array by groups.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
// { Driver Code Starts
//Initial template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function template for C++
class Solution{
public:
//Function to reverse every sub-array group of size k.
void reverseInGroups(vector<long long>& arr, int n, int k){
// code here
int i;
for(i=k-1;i<n;i+=k){
rev(arr,i-k+1,i);
}
rev(arr,i-k+1,n-1);
}
void rev(vector<long long>& arr, int i, int j){
while(i<j){
swap(arr[i],arr[j]);
i++;
j--;
}
}
};
// { Driver Code Starts.
int main() {
int t;
cin >> t;
while(t--){
int n;
cin >> n;
vector<long long> arr;
int k;
cin >> k;
for(long long i = 0; i<n; i++)
{
long long x;
cin >> x;
arr.push_back(x);
}
Solution ob;
ob.reverseInGroups(arr, n, k);
for(long long i = 0; i<n; i++){
cout << arr[i] << " ";
}
cout << endl;
}
}
// } Driver Code Ends