Reversal algorithm for array rotation in C++
In this tutorial, we are going to learn about Reversal algorithm for array rotation in C++. In this problem, we have to rotate the array from a particular point let’s say it (k) in the clockwise direction.
Let us understand the problem by taking an example:
Let the given array be:
1->2->3->4->5
And the point from which we have to rotate the array be k which is equal to 2.
After the first rotation array will be like:
2->3->4->5->1
and after second rotation array will be like:
3->4->5->1->2
which is our required answer.
The idea to solve this problem is very simple. First, iterate the array from given index=k to end of the array and print it. Then iterate the array from index=0 to the given index k and print it. We will get the required answer. Let us try to implement the above idea in our code.
Program for Reversal algorithm for array rotation
Cpp source code:
// Reversal algorithm for array rotation in C++ #include<bits/stdc++.h> using namespace std; int main() { int n; cout<<"Enter length of array: "; cin>>n; int a[n]; cout<<"\nEnter array elements:\n"; for(int i=0;i<n;i++) { cin>>a[i]; } int k; cout<<"\nEnter the index from which you want to rotate array: "; cin>>k; cout<<"\nArray after rotation:\n"; for(int i=k;i<n;i++) { cout<<a[i]<<" "; } for(int i=0;i<k;i++) { cout<<a[i]<<" "; } cout<<"\n"; return 0; }
Input/Output:
Enter length of array: 5 Enter array elements: 1 2 3 4 5 Enter the index from which you want to rotate array: 2 Array after rotation: 3 4 5 1 2
The time complexity of the above solution is O(n).
You may also learn:
Program to calculate percentile of an array in C++
How to Reverse the Elements of an Array in C++
Do not forget to comment if you find anything wrong in the post or you want to share some information regarding the same.
Leave a Reply