×

DS - Basics

DS - Array

DS - Linked List

DS - Stack

DS - Queue

DS Hashing

DS Tree

DS - Graph

DS Programs Using C/C++

DS - Miscellaneous Topics

Reversal algorithm for right rotation of an array

Reversal algorithm for right rotation of an array, and its implementation using C++ program.
Submitted by Vikneshwar GK, on February 26, 2022

Consider an integer array, of size n and a rotation value k. The task at hand is to rotate the array in a clockwise direction by k times, i.e., place the last k elements at the beginning of the array by pushing the remaining elements to the end.

Example:

Input:
array[]= {1, 2, 3, 4, 5}
k = 3

Output:
array[] = {3, 4, 5, 1, 2}
 
Input:
array[]= {10, 20, 30, 40, 50}
k = 1

Output:
array[]= {50, 10, 20, 30, 40}

Solution:

This algorithm divides the array into two groups. The first group consists of array elements from 0 to k-1 and the second group from d to n-1, where n is the length of the array. It involves the following steps:

  • Reverse the array completely
  • Reverse the array[0..d-1]
  • Reverse the array[d..n-1]
  • Print the array

Consider the following example:

If array[] = {1, 2, 3, 4, 5, 6} and d = 3,
After 1st reversal, array will be array[] = {6, 5, 4, 3, 2, 1}
After 2nd reversal, array will be array[] = {4, 5, 6, 3, 2, 1}
After 3rd reversal, array will be array[] = {4, 5, 6, 1, 2, 3}

C++ Implementation:

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

// Function to reverse the array
void arrayReverse(int array[], int begin, int end)
{
    while (begin < end) {
        int temp = array[begin];
        array[begin] = array[end];
        array[end] = temp;
        begin++;
        end--;
    }
}

// Function to rotate the array by reversing
void rotate(int array[], int d, int length)
{
    if (d == 0)
        return;

    // case to handle when d greater than length
    d = d % length;

    // array reverse
    arrayReverse(array, 0, length - 1);
    arrayReverse(array, 0, d - 1);
    arrayReverse(array, d, length - 1);
}

//Function to print the array
void printArray(int array[], int length)
{
    for (int i = 0; i < length; i++)
        cout << array[i] << " ";
    cout << endl;
}

// Main function
int main()
{
    int array[100], N, d;
    
    cout << "Enter Number of elements: ";
    cin >> N;

    for (int i = 0; i < N; i++) {
        cout << "Enter element " << i + 1 << ":";
        cin >> array[i];
    }
    cout << "Enter the value of d: ";
    cin >> d;

    rotate(array, d, N);
    cout << "Rotated Array" << endl;
    printArray(array, N);

    return 0;
}

Output:

Enter Number of elements: 6
Enter element 1:2
Enter element 2:4
Enter element 3:5
Enter element 4:6
Enter element 5:9
Enter element 6:10
Enter the value of d: 3
Rotated Array
6 9 10 2 4 5 

Time Complexity: O(n), where n is the length of the array.


Related Tutorials



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.