Puzzle DE41


Exchange the first N/2 elements of an array with the last N/2 elements

[H-7] Write a function that swaps the first half of an array with the last half. Within each half of the array, keep the elements in their original order. If the array has an odd number of characters, the middle element remains where it is. Here is a sample run:

Original:
   0    1    2    3    4    5    6    7    8    9
  10   11   12   13   14   15   16   17   18

Swap Halves:
  10   11   12   13   14   15   16   17   18    9
   0    1    2    3    4    5    6    7    8

Here is a testing framework you can copy and paste into a source file:

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

/* Puzzle D41 -- swap the top half of an array with the bottom half
|
|  Within each half, keep the elements in their original order.
|  If the array has an odd number of elements, the middle element
|  remains where it is.
*/
void swapHalves( int size, int arr[] )
{
}

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 = 19;
  int x[ SIZE ];
  
  printf("Original:\n");
  fillArrayInOrder( SIZE, x );
  printArray( SIZE, x );

  printf("\nSwap Halves: \n");
  swapHalves( SIZE, x );
  printArray( SIZE, x );
  printf("\n\n");
  
  system("PAUSE");	 /* As always, remove this if you don't need it */
  return 0;
}



Answer         Next Page         Previous Page Home