-
Notifications
You must be signed in to change notification settings - Fork 22
/
Reverse Array in groups
62 lines (51 loc) · 1.35 KB
/
Reverse Array in groups
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
/*
Given an array arr[] of positive integers of size N. Reverse every sub-array of K group elements.
Input:
The first line of input contains a single integer T denoting the number of test cases. Then T test cases follow. Each test case consist of two
lines of input. The first line of each test case consists of an integer N(size of array) and an integer K separated by a space. The second line
of each test case contains N space separated integers denoting the array elements.
Output:
For each test case, print the modified array.
Constraints:
1 ≤ T ≤ 200
1 ≤ N, K ≤ 107
1 ≤ A[i] ≤ 1018
Example:
Input
1
5 3
1 2 3 4 5
Output
3 2 1 5 4
Explanation:
Testcase 1: Reversing groups in size 3, first group consists of elements 1, 2, 3. Reversing this group, we have elements in order as 3, 2, 1.*/
//program
#include <bits/stdc++.h>
using namespace std;
void swap(int *a, int *b)
{
int *t=a;
*a=*b;
*b=*t;
}
void reverse(int arr[], int n, int k)
{
for (int i = 0; i < n; i += k)
{
int left = i;
int right = min(i + k - 1, n - 1);
while (left < right)
swap(arr[left++], arr[right--]);
}
}
int main() {
int t; cin>>t; while(t--)
{
int n,k; cin>>n>>k;
int a[n],i; for(i=0;i<n;i++) cin>>a[i];
reverse(a,n,k);
for(i=0;i<n;i++) cout<<a[i]<<" ";
cout<<endl;
}
return 0;
}