Write a program to rotate the array.
Left Rotation: Left rotation means to rotate the array towards the left of the array. It means to rotate the array in the clockwise direction.
Right Rotation: Right rotation means to rotate the array towards the right of the array. It means to rotate the array in the anti-clockwise direction
Example:
Input: arr[]={3,2,1,5,4}
Output: Left Rotated Array is : 2 1 5 4 3
Approach: Left Rotation of an Array
C++
#include <bits/stdc++.h>using namespace std;void leftRotate(vector<int> &arr){int temp = arr[0];int i = 0;for (i = 0; i < arr.size() - 1; i++){arr[i] = arr[i + 1];}arr[i] = temp;}int main(){vector<int> arr = {3, 2, 1, 5, 4};leftRotate(arr);cout << "Left Rotated Array is : ";for (int i = 0; i < arr.size(); i++){cout << arr[i] << " ";}return 0;}
Example:
Input: arr[]={3,2,1,5,4}
Output: Right Rotated Array is : 4 3 2 1 5
Approach: Right rotation of an Array
C++
#include <bits/stdc++.h>using namespace std;void rightRotate(vector<int> &arr){int temp = arr[arr.size() - 1];int i = arr.size() - 1;for (i = arr.size() - 1; i > 0; i--){arr[i] = arr[i - 1];}arr[0] = temp;}int main(){vector<int> arr = {3, 2, 1, 5, 4};rightRotate(arr);cout << "Right Rotated Array is : ";for (int i = 0; i < arr.size(); i++){cout << arr[i] << " ";}return 0;}
No comments:
Post a Comment