Reversal Algorithm for Right Rotation of an Array using C++

C++Server Side ProgrammingProgramming

In this article, we will understand the Reversal algorithm to rotate a given array by k-elements to the right, for example −

Input : arr[ ] = { 4, 6, 2, 6, 43, 7, 3, 7 }, k = 4
Output : { 43, 7, 3, 7, 4, 6, 2, 6 }
Explanation : Rotating each element of array by 4-element to the right gives { 43, 7, 3, 7, 4, 6, 2, 6 }.

Input : arr[ ] = { 8, 5, 8, 2, 1, 4, 9, 3 }, k = 3
Output : { 4, 9, 3, 8, 5, 8, 2, 1 }

Approach to find The Solution

You can easily solve this problem by shifting each element to the right and repeating this procedure k-times. But this will take more time as its time complexity will be O(k * N).

Reversal Algorithm: Reversal reverses an array, and rotating an array can be done by reversing some element range. According to this algorithm −

  • First, reverse the whole array.
  • Modify k with the modulus of k with N(array size) because k is greater than N.
  • Reverse the first k elements of the array to get in order.
  • Then reverse the range of remaining elements, i.e., from k to N-1.

Example

using namespace std;
#include <bits/stdc++.h>

void reverse(int nums[], int start,int end) {
   int temp=0;
   // reversing array with swapping start element with end element.
   while(start<=end){
      temp=nums[end];
      nums[end]=nums[start];
      nums[start]=temp;
      start++;
      end--;
   }
}

int main() {
   int arr[] = {4, 6, 2, 6, 43, 7, 3, 6, 2, 4, 5 };

   int N = sizeof(arr)/sizeof(arr[0]);

   int k = 4;
   // reversing whole array
   reverse(arr, 0, N-1);
   k = k%N;
   // reversing element range of 0 to k-1.

   reverse(arr, 0, k-1);
   // reversing element range of k to last element.
   reverse(arr, k, N-1);
   cout << "Array after rotating by k-elements : ";
   for(int i = 0;i<N;i++)
      cout << arr[i] << " ";
   return 0;
}

Output

Array after rotating by k-elements : 6 2 4 5 4 6 2 6 43 7 3

Conclusion

In this article we discussed the problem of right rotation of an array by k-elements using the Reversal algorithm.We discussed what reversal algorithm is and how it can be implemented to solve this problem. We also discussed C++ code to solve this problem. We can write this code in any other language like C, Java, Python, etc. Hope you find this article helpful.

raja
Published on 29-Nov-2021 10:07:24

Advertisements