Examples:
Input:
arr[ ]= {1, 2, 3,4,5}
index: 2
Output:
arr[ ]= {4, 5, 1, 2, 3}
Input:
arr[ ]= { 10, 20, 30 , 40 , 50}
index : 3
Output:
arr[ ]= {30, 50, 40, 10, 20}
#include <bits/stdc++.h>
using namespace std;
// Function to reverse the arr
void arrReverse(int arr[], int l, int r)
{
while (l < r)
{
int temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
l++;
r--;
}
}
// Function to rotate the arr by reversing
void rotate(int arr[], int d, int length)
{
if (d == 0)
return;
// case to handle when d greater than length
d = d % length;
// arr reverse
arrReverse(arr, 0, length - 1);
arrReverse(arr, 0, d - 1);
arrReverse(arr, d, length - 1);
}
// Function to print the arr
void printArr(int arr[], int length)
{
for (int i = 0; i < length; i++)
cout << arr[i] << " ";
cout << endl;
}
// Main function
int main()
{
int arr[100], N, index ;
cout << "Enter size of array : ";
cin >> N;
for (int i = 0; i < N; i++)
{
cin >> arr[i];
}
cout << "Enter the value of index : ";
cin >> index;
rotate(arr, index , N);
cout << "Rotated array" << endl;
printArr(arr, N);
return 0;
}
Output:
Enter size of arr : 5
1 2 3 4 5
Enter the value of d: 2
Rotated arr
4 5 1 2 3
0 Comments