Monday, 18 September 2017

Array Rotation using Reversal Algorithm


Array Rotation Using Revesal Algorithm :

Given an array of N size. The task is to rotate array by d elements where d is less than or equal to N.

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

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

Algorithm:

step1 : Reverse the elements starting from index 0 to d-1.
step2 : Reverse the elements from index d to n-1.
step3 : Reverse the entire array



For the given sample input,
After step 1:
   arr[]={2,1,3,4,5,6,7}
After step 2:
   arr[]={2,1,7,6,5,4,3}
After step 3:
   arr[]={3,4,5,6,7,1,2}

Program:

 

#include <stdio.h>


void reverse(int a[],int start,int end)
{      

      int temp;

      while(start<end)

       {

            temp=a[start];
            a[start]=a[end];
            a[end]=temp;
            start++;
            end--;

        }

}
void RotateArray(int a[],int n,int d)
{
         reverse(a,0,d-1);
         reverse(a,d,n-1);
         reverse(a,0,n-1);
}


void printArray(int a[],int n)
{
     int i;
         for(i=0;i<n;i++)

     printf("%d ",a[i]);
     printf("\n");
}


int main() 

{
        int n,i,d;

        scanf("%d",&n);
        int a[n];
        for(i=0;i<n;i++)

             scanf("%d",&a[i]);

        scanf("%d",&d);
        RotateArray(a,n,d);
        printArray(a,n);
        return 0;
}

No comments:

Post a Comment