Array rotation (method -2)


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, n=7

Output  : {2,3,4,5,6,7,1,2}

Solution : 


// In  this method we create an extra array ar[] of size d and we store d element of  array arr[] in array ar[] and we initilize arr[i] with arr[d+i] and atlast we store ar[] element at last in arr[].

#include<iostream>

using namespace std;

void rotate(int arr[],int ar[],int n,int d)

{

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

    ar[i]=arr[i];

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

    arr[i]=arr[i+d];

    for(int i=n-d,j=0;i<n;i++,j++)

    arr[i]=ar[j];


}

void print(int arr[],int n)

{

   

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

      cout<<arr[i];


}

int main()

{

   int n,d;

   cout<<"Enter the size of array : ";cin>>n;

   cout<<"Enter the value of d (no of rotations) : ";cin>>d;

   if(d>n)

   d%=n;

   int arr[n];

   int ar[d];

   cout<<"Enter the element of array : "<<endl;

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

      cin>>arr[i];

   rotate(arr,ar,n,d);

   print(arr,n);


}



Time complixity - O(n)


Comments