cyclically rotate array by 1
Wed Nov 13 2024 16:31:04 GMT+0000 (Coordinated Universal Time)
Saved by
@Pavan_05
#include <iostream>
using namespace std;
// here basically i am just storing the last element in a temporary variable and looping from last element to 2nd element and assigning last 2nd element to last element and finally when loop is over i am just assigning back the temp variable to 1st element
void rotateby1(int arr[], int n){
int temp = arr[n-1];
for(int i = n-1; i>0; i--){
arr[i] = arr[i-1];
}
arr[0] = temp;
}
// here i took two pointers to 1st and last element, and swapping the 1st with last element but last element is freezed and only the 1st element is being incremented.
void rotatetwopointer(int arr[], int n){
int l = 0;
int r = n-1;
for(int i=0; i<n-1; i++){
swap(arr[i], arr[r]);
}
}
//here I am rotating the 1st n-k element and then rotating the whole array
void rotatereverse(int arr[], int n, int k){
for(int i=0, j=n-k-1; i<j; i++, j-- ){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
for(int i=0, j=n-1; i<j; i++, j--){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr)/sizeof(arr[0]);
rotatereverse(arr,n,1);
for(int i=0; i<n; i++){
cout<<arr[i];
}
return 0;
}
content_copyCOPY
Comments