Monday, November 25, 2013

Circular right shift of an array.

Problem:
Write a program to do circular right shift of an array.

e.g. Original array: 1 2 3 4 5 6 7
Circular right shift by 3 gives: 5 6 7 1 2 3 4

Algorithm:
  • If the value of the Shift is greater than the Size of the Array, overwrite the shift value by the Remainder of Shift divided by Size of the array.
  • Take a local array with size equal to the Shift value.
  • Store the part of array to be shifted in local array.
  • Shift the original array to the right by the value equal to Shift.
  • Copy the local array in the front of the original array starting at index zero.

#include "stdio.h"

#define SIZE 9

void circularRightShift(int *arr, int size, int shift)
{
 if ((shift == size) || (shift == 0))
     printf("No need to shift: Shift value and Size of array is same. \n");
 if (shift > size)
     shift = shift%size;

 int localarr[shift];

 for (int i = (size-shift); i < size; i++)
 {
     localarr[i - (size-shift)] = arr[i];
 }
 
 for (int j = (size-shift-1); j >= 0; j--)
 {
     arr[j+shift] = arr[j];
 }
 
 for(int k = 0; k < shift; k++)
 {
     arr[k] = localarr[k];
 }
}
int main(void)
{
    int arr[SIZE] = {1,2,3,4,5,6,7,8,9};
 
    circularRightShift(arr, SIZE, 20);

    for (int i = 0; i    {
       printf("  %d",arr[i]);
    }
    printf("\n");
    return 0;
}

No comments: