Skip to content

Commit ff02627

Browse files
committed
program to rotate an array clockwise and anti-clockwise
1 parent 3798114 commit ff02627

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

General Programs/ArrayRotation.cpp

+67
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,75 @@ using namespace std;
44

55
//array rotation
66

7+
void Rotate(int arr[],int d,int n)
8+
{
9+
int temp[d];
10+
//copying items in a temp array
11+
for(int i = 0 ; i < d; i++)
12+
{
13+
temp[i] = arr[i];
14+
15+
}
16+
17+
for(int i = 0 ; i < n ;i++)
18+
{
19+
arr[i] = arr[i+d];
20+
}
21+
22+
for(int i = 0 ; i < d ; i++)
23+
{
24+
arr[n] = temp[i];
25+
}
26+
27+
for(int i = 0 ; i < n ; i++)
28+
{
29+
cout<<arr[i]<<" ";
30+
}
31+
32+
33+
}
34+
35+
void leftRotateByOne(int arr[],int n)
36+
{
37+
int temp = arr[0],i;
38+
39+
for(i = 0 ; i < n-1 ;i++)
40+
{
41+
arr[i] = arr[i+1];
42+
}
43+
44+
arr[i] = temp; //now first element is added to the last
45+
}
46+
47+
48+
void RightRotateByOne(int arr[],int n)
49+
{
50+
int temp = arr[n-1],i;
51+
52+
for(i = n-1 ; i > 0 ; i--)
53+
{
54+
arr[i] = arr[i-1];
55+
}
56+
57+
arr[i] = temp;
58+
59+
}
60+
void RotateEffi(int arr[],int d,int n)
61+
{
62+
for(int i = 0 ; i < d;i++)
63+
RightRotateByOne(arr,n);
64+
65+
for(int j = 0 ; j < n ; j++)
66+
{
67+
cout<<arr[j]<<" ";
68+
}
69+
}
70+
//T(n) = O(n*d)
771

872
int main()
973
{
74+
int arr[] = {1,2,3,4,5,6,7};
75+
int size = sizeof(arr)/sizeof(arr[0]);
76+
RotateEffi(arr,3,size);
1077
return 0;
1178
}

0 commit comments

Comments
 (0)