forked from TECHOUS/DSKaKhel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrotateArrayBy_K.cpp
More file actions
62 lines (44 loc) · 1.25 KB
/
rotateArrayBy_K.cpp
File metadata and controls
62 lines (44 loc) · 1.25 KB
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
#include<iostream>
#include<limits>
#include<algorithm>
using namespace std;
/* This is the basic algorithm with :
Time Complexity O(n * k) where k is the no of elements to rotate it by
Space Complexity = 0(n);
*/
void rotateArrayByK(int *arr , int size, int k){
int j = 1;
while(k--){
// take the first element of the array [ before or after rotation ]
int temp = arr[0];
// shift the array by 1 element array[0th index ] = its next index and so on.
for(int i = 0 ; i < size - 1 ; i++){
// Shifting the elements to the left by 1 element
arr[i] = arr[i+1];
}
// attaching the first to the end by 1 rotation
// replace the last element with the first for anticlockwise rotation
arr[size-1] = temp;
}
}
void printArr(int *arr,int size){
for(int i = 0 ; i < size ; i++){
cout<<arr[i]<<endl;
}
}
int main(){
int size,k;
cout<<"Enter the size"<<endl;
cin>>size;
cout<<"Enter the no of elements to rotate by"<<endl;
cin>>k;
int *arr = new int(size);
cout<<"Enter the elements "<<endl;
for(int i = 0 ; i < size ; i++){
cin>>arr[i];
}
cout<<"performing the rotation"<<endl;
rotateArrayByK(arr,size,k);
cout<<"The array after rotating is "<<endl;
printArr(arr,size);
}