Rotation of Elements of Array - Left and Right in C++
Understanding Array Rotation
Array rotation involves shifting elements either to the left or right by a specified number of positions.
We will explore three different methods to perform left and right rotation in C++.
Method 1: Using Temporary Array
#include <iostream> using namespace std; void leftRotate(int arr[], int n, int d) { int temp[d]; for (int i = 0; i < d; i++) temp[i] = arr[i]; for (int i = 0; i < n - d; i++) arr[i] = arr[i + d]; for (int i = 0; i < d; i++) arr[n - d + i] = temp[i]; } void rightRotate(int arr[], int n, int d) { int temp[d]; for (int i = 0; i < d; i++) temp[i] = arr[n - d + i]; for (int i = n - 1; i >= d; i--) arr[i] = arr[i - d]; for (int i = 0; i < d; i++) arr[i] = temp[i]; } void printArray(int arr[], int n) { for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << endl; } int main() { int arr[] = {1, 2, 3, 4, 5}; int n = 5; leftRotate(arr, n, 2); cout << "Array after left rotation: "; printArray(arr, n); rightRotate(arr, n, 2); cout << "Array after right rotation: "; printArray(arr, n); return 0; }
Array after left rotation: 3 4 5 1 2
Array after right rotation: 1 2 3 4 5
Method 2: Using Reversal Algorithm
#include <iostream> using namespace std; void reverse(int arr[], int start, int end) { while (start < end) { swap(arr[start], arr[end]); start++; end--; } } void leftRotate(int arr[], int n, int d) { reverse(arr, 0, d - 1); reverse(arr, d, n - 1); reverse(arr, 0, n - 1); } void rightRotate(int arr[], int n, int d) { reverse(arr, 0, n - 1); reverse(arr, 0, d - 1); reverse(arr, d, n - 1); } void printArray(int arr[], int n) { for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << endl; } int main() { int arr[] = {1, 2, 3, 4, 5}; int n = 5; leftRotate(arr, n, 2); cout << "Array after left rotation: "; printArray(arr, n); rightRotate(arr, n, 2); cout << "Array after right rotation: "; printArray(arr, n); return 0; }
Array after left rotation: 3 4 5 1 2
Array after right rotation: 1 2 3 4 5
Method 3: Rotating One by One
#include <iostream> using namespace std; void leftRotateOne(int arr[], int n) { int temp = arr[0]; for (int i = 0; i < n - 1; i++) arr[i] = arr[i + 1]; arr[n - 1] = temp; } void rightRotateOne(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; } void leftRotate(int arr[], int n, int d) { for (int i = 0; i < d; i++) leftRotateOne(arr, n); } void rightRotate(int arr[], int n, int d) { for (int i = 0; i < d; i++) rightRotateOne(arr, n); } void printArray(int arr[], int n) { for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << endl; } int main() { int arr[] = {1, 2, 3, 4, 5}; int n = 5; leftRotate(arr, n, 2); cout << "Array after left rotation: "; printArray(arr, n); rightRotate(arr, n, 2); cout << "Array after right rotation: "; printArray(arr, n); return 0; }
Array after left rotation: 3 4 5 1 2
Array after right rotation: 1 2 3 4 5