C++ Program to Rotate Array using Reverse function














































C++ Program to Rotate Array using Reverse function



Rotate Array using the Reverse function

Given an unsorted array arr[] of size N, rotate it by D elements in the counter-clockwise direction. 

The Approach is to use the reverse function to rotate the array counter-clockwise d times.

Example:
n = 1, 2, 3, 4 ,5  to rotate it 2 times
The rotated array will be 3, 4, 5, 1, 2

1)We can do this first reverse the array
n = 5, 4, 3, 2, 1
2)Now reverse array d position to last position
n = 5,4,3,1,2
3)Now reverse the first position to  n-d position
n = 3, 4 ,5, 1, 2

Time Complexity: O(n)
Space Complexity: O(1)

Code
#include<bits/stdc++.h>
using namespace std; void rotateArr(int arr[], int d, int n){
d = d % n;
if(d > 0){ reverse(arr, arr+n); reverse(arr, arr+n-d); reverse(arr+n-d, arr+n); }
} int main(){
int arr[] = {1,2,3,4,5};
int n = sizeof(arr)/arr[0]; rotate(arr,
rotate(arr, 2, 5);
for(auto i : arr)
cout << i << " ";cout << endl;
return 0; }

Output :  3 4 5 1 2


Comments