-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathArrayRotation.cpp
126 lines (93 loc) · 1.61 KB
/
ArrayRotation.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include<iostream>
using namespace std;
/*array rotation
1)Rotating one by one
2)Reversal algorithm
*/
void reverseArr(int arr[],int start,int end)
{
while(start < end)
{
swap(arr[start++],arr[end--]);
}
}
void RotateSimpleClock(int arr[],int d,int n)
{
reverseArr(arr,n-d,n-1);
reverseArr(arr,0,n-d-1);
reverseArr(arr,0,n-1);
for(int i = 0 ; i < n ; i++)
{
cout<<arr[i]<<" ";
}
}
void RotateSimpleAntiClock(int arr[],int d,int n)
{
reverseArr(arr,0,d-1);
reverseArr(arr,d,n-1);
reverseArr(arr,0,n-1);
for(int i = 0 ; i < n ; i++)
{
cout<<arr[i]<<" ";
}
}
void Rotate(int arr[],int d,int n)
{
int temp[d];
//copying items in a temp array
for(int i = 0 ; i < d; i++)
{
temp[i] = arr[i];
}
for(int i = 0 ; i < n ;i++)
{
arr[i] = arr[i+d];
}
for(int i = 0 ; i < d ; i++)
{
arr[n] = temp[i];
}
for(int i = 0 ; i < n ; i++)
{
cout<<arr[i]<<" ";
}
}
void leftRotateByOne(int arr[],int n)
{
int temp = arr[0],i;
for(i = 0 ; i < n-1 ;i++)
{
arr[i] = arr[i+1];
}
arr[i] = temp; //now first element is added to the last
}
void RightRotateByOne(int arr[],int n)
{
int temp = arr[n-1],i;
for(i = n-1 ; i > 0 ; i--)
{
arr[i] = arr[i-1];
}
arr[i] = temp;
}
void RotateEffi(int arr[],int d,int n)
{
for(int i = 0 ; i < d;i++)
RightRotateByOne(arr,n);
for(int j = 0 ; j < n ; j++)
{
cout<<arr[j]<<" ";
}
}
//T(n) = O(n*d)
rotate()
int main()
{
int arr[] = {1,2,3,4,5,6,7};
int size = sizeof(arr)/sizeof(arr[0]);
RotateSimpleClock(arr,2,size);
cout<<endl;
int arr1[] = {1,2,3,4,5,6,7};
RotateSimpleAntiClock(arr1,2,size);
return 0;
}