-
Notifications
You must be signed in to change notification settings - Fork 72
/
rotate-array
65 lines (50 loc) · 1.24 KB
/
rotate-array
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
/*Given an unsorted array arr[] of size N, rotate it by D elements (clockwise).
Input:
The first line of the input contains T denoting the number of testcases. First line of each test case contains two space separated elements, N denoting the size of the array and an integer D denoting the number size of the rotation. Subsequent line will be the N space separated array elements.
Output:
For each testcase, in a new line, output the rotated array.
Constraints:
1 <= T <= 200
1 <= N <= 107
1 <= D <= N
0 <= arr[i] <= 105
Example:
Input:
2
5 2
1 2 3 4 5
10 3
2 4 6 8 10 12 14 16 18 20
Output:
3 4 5 1 2
8 10 12 14 16 18 20 2 4 6
Explanation :
Testcase 1: 1 2 3 4 5 when rotated by 2 elements, it becomes 3 4 5 1 2.*/
//Solution
#include <bits/stdc++.h>
using namespace std;
void leftRotatebyOne(int arr[], int n)
{
int temp = arr[0], i;
for (i = 0; i < n - 1; i++)
arr[i] = arr[i + 1];
arr[n-1] = temp;
}
void leftRotate(int arr[], int d, int n)
{
for (int i = 0; i < d; i++)
leftRotatebyOne(arr, n);
}
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
leftRotate(arr, 2, n);
printArray(arr, n);
return 0;
}