-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharrayRotationAlgo.cpp
More file actions
44 lines (36 loc) · 807 Bytes
/
arrayRotationAlgo.cpp
File metadata and controls
44 lines (36 loc) · 807 Bytes
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
#include<bits/stdc++.h>
using namespace std;
// Array Rotation -- By Reversal Algorithm
// 1 2 3 4 5 --> rotate 2 elements
// 3 4 5 1 2 --> ans
// Algo
// 1 2 3 4 5
// 1 2 | 3 4 5 --> Divided into parts
// 2 1 3 4 5
// 2 1 5 4 3 --> swap 3 and 5
// 3 4 5 1 2 --> Ans
void reve(int arr[], int start, int end){
while (start < end){
swap(arr[start++], arr[end--]);
}
}
void leftToRight(int a[], int n, int k){
reve(a, 0, k-1);
reve(a, k, n-1);
reve(a, 0, n-1);
}
void rightToLeft(int a[], int n, int k){
reve(a, 0, n-1);
reve(a, 0, k-1);
reve(a, k, n-1);
}
int main() {
int a[] = {1, 2, 3, 4, 5};
int n = 5;
int k = 2; // no of element to be rotated
rev(a, n, k);
for (int i=0;i<n;i++){
cout << a[i] << " ";
}
return 0;
}