Puzzle DD37


Shift array elements N positions right; the first N elements get 0

[M-12] Write a function that moves each element in an integer array N positions to the right. The first N positions are filled with zero, and the last N elements are discarded.

 777    1    2    3    4    5    6    7    8    9
  10   11   12   13   14   15   16   17   18   19

Right Shifted by 5 positions:
   0    0    0    0    0  777    1    2    3    4
   5    6    7    8    9   10   11   12   13   14

Decide what to do if the shift amount is negative or zero, or larger than the size of the array.

An easy way to do this is to call the function that shifts by one position N times. But this is N times slower than an efficient implementation. Try to come up with an efficient way to do this.

Here is a testing framework:

#include <stdio.h>
#include <stdlib.h>

/* Puzzle D37 -- shift every array element N positions right; */
/*               the first N elements get 0 */

void shiftRightNArray( int size, int arr[], int shift )
{
}

void shiftRightArray( int size, int arr[] )
{
  int j;
  for ( j=size-1; j>=1; j-- )
      arr[j] = arr[j-1];
      
  arr[0] = 0;
}

void fillArrayInOrder( int size, int arr[] )
{
  int j;
  
  for ( j=0; j<size; j++ )
  {
    arr[j] = j;
  }
}

void printArray( int size, int arr[] )
{
  const int N = 10;
  int j;
  
  for ( j=0; j<size; j++ )
  {
    if ( j%N == N-1 )
      printf("%4d\n", arr[j] );
    else
      printf("%4d ", arr[j] );    
  }
}

int main()
{
  const int SIZE = 20;
  int shift = 5;
  int x[ SIZE ];
  
  fillArrayInOrder( SIZE, x );
  x[0] = 777;
  printArray( SIZE, x );
  printf("\nRight Shifted by %d positions:\n", shift);
  shiftRightNArrayAlt( SIZE, x, shift );
  printArray( SIZE, x );
    
  printf("\n\n");
  return 0;
}



Answer         Next Page         Previous Page Home