home *** CD-ROM | disk | FTP | other *** search
/ Jason Aller Floppy Collection / 98.img / LCNOW2.ZIP / EXAMPLES / XSORT.C < prev   
C/C++ Source or Header  |  1988-08-02  |  2KB  |  91 lines

  1. /*
  2.  * X S O R T
  3.  *
  4.  * Sort an array of numbers by using a simple exchange sort.
  5.  */
  6.  
  7. #define SHOWME
  8.  
  9. #include <stdio.h>
  10.  
  11. void ExchangeSort(int *, unsigned int);
  12.  
  13. int
  14. main(void)
  15. {
  16.     int n;          /* loop control variable */
  17.     int *ptr;       /* integer pointer */
  18.     int size;       /* calculated array size in elements */
  19.  
  20.     /* array data */
  21.     static int numbers[] = {
  22.         82, 30, 12, 1, -6
  23.     };
  24.  
  25.     /*
  26.      * Calculate the array size and display the
  27.      * array in its initial condition.
  28.      */
  29.     size = sizeof numbers / sizeof (int);
  30.     puts("Array before sorting:");
  31.     for (n = size, ptr = numbers; n-- > 0; ++ptr)
  32.         printf("%5d  ", *ptr);
  33.     putchar('\n');
  34.     putchar('\n');
  35.  
  36.     /*
  37.      * Sort the array.
  38.      */
  39.     ExchangeSort(numbers, size);
  40.  
  41.     /*
  42.      * Display the array after sorting.
  43.      */
  44.     puts("\nArray after sorting:");
  45.     for (n = size, ptr = numbers; n-- > 0; ++ptr)
  46.         printf("%5d  ", *ptr);
  47.     putchar('\n');
  48.  
  49.     return (0);
  50. }
  51.  
  52.  
  53. /*
  54.  * ExchangeSort()
  55.  *
  56.  * A simple exchange sort function
  57.  */
  58.  
  59. void
  60. ExchangeSort(int *array, unsigned int nelem)
  61. {
  62.     int *p, *q;      /* array indexes */
  63.     int temp;        /* buffer for exchanges */
  64. #if defined (SHOWME)
  65.     int loopcount = 0;
  66.     int *ptr;
  67. #endif
  68.  
  69.     for (p = array; p < array + nelem - 1; ++p) {
  70. #if defined (SHOWME)
  71.         printf("Loop %d:\n", ++loopcount);
  72. #endif
  73.         for (q = p + 1; q < array + nelem; ++q) {
  74.             if (*p > *q) {
  75.                 temp = *p;
  76.                 *p = *q;
  77.                 *q = temp;
  78.             }
  79. #if defined (SHOWME)
  80.             /*
  81.              * Show partially sorted array after each
  82.              * pass of the inner loop.
  83.              */
  84.             for (ptr = array; ptr < array + nelem; ++ptr)
  85.                 printf("%5d  ", *ptr);
  86.             putchar('\n');
  87. #endif
  88.         }
  89.     }
  90. }
  91.