-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPaper3_question2.cpp
62 lines (50 loc) · 1.02 KB
/
Paper3_question2.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
// Q2. Program for array rotation.
// Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements.
// Rotation of the above array by 2 will make array
#include <bits/stdc++.h>
using namespace std;
int gcd(int a, int b)
{
if (b == 0)
return a;
else
return gcd(b, a % b);
}
// LEFT ROTATION
void leftRotate(int arr[], int d, int n)
{
/* To handle if d >= n */
d = d % n;
int g_c_d = gcd(d, n);
for (int i = 0; i < g_c_d; i++) {
/* move i-th values of blocks */
int temp = arr[i];
int j = i;
while (1) {
int k = j + d;
if (k >= n)
k = k - n;
if (k == i)
break;
arr[j] = arr[k];
j = k;
}
arr[j] = temp;
}
}
// PRINTING THE ARRAY
void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
}
// MAIN FUNCTION
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
// Function calling
leftRotate(arr, 2, n);
printArray(arr, n);
return 0;
}