Array rotation using reversible algorithm in C++

Question - 

Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements.

Example - 

Input : arr[] = {1,2,3,4,5,6,7}  , d=2

output - arr[] = {3,4,5,6,7,1,2}

  

Solution-  


 //logic - > we have an array ,d and n...first we reverse array element from 0 to d-1 and than reverse element from d to n-1 and finally we reverse all array element and we got rotated array.



//array rotation using reversible algorithm

#include<iostream>

using namespace std;

void printarray(int arr[],int n)

{

    for(int i=0;i<n;i++)

    cout<<arr[i]<<" ";

    cout<<endl;

}

void reverserarray(int arr[],int start,int end)

{

    while(start<end){

        int temp=arr[start];

        arr[start]=arr[end];

        arr[end]=temp;

        start++;

        end--;

    }

}

void rotatearrar(int arr[],int d,int n)

{


    reverserarray(arr,0,d-1);

    reverserarray(arr,d,n-1);

    reverserarray(arr,0,n-1);


}

int main()

{

    int n;

    cout<<"Enter the number of elements : ";cin>>n;

    int d;

    cout<<"Enter the number of rotations : ";cin>>d;

    int arr[n];

    for(int i=0;i<n;i++)

    cin>>arr[i];

    d%=n;

    if(d!=0)

    rotatearrar(arr,d,n);

    printarray(arr,n);

}



Time complixity - O(n)


code on online compiler

Comments