home *** CD-ROM | disk | FTP | other *** search
- /****************************************************************************/
- /* */
- /* Sample Program 03 : SAMPLE03.C */
- /* */
- /* COPYRIGHT: */
- /* ---------- */
- /* Copyright (C) International Business Machines Corp., 1991, 1993. */
- /* */
- /* DISCLAIMER OF WARRANTIES: */
- /* ------------------------- */
- /* The following [enclosed] code is sample code created by IBM */
- /* Corporation. This sample code is not part of any standard IBM product */
- /* and is provided to you solely for the purpose of assisting you in the */
- /* development of your applications. The code is provided "AS IS", */
- /* without warranty of any kind. IBM shall not be liable for any damages */
- /* arising out of your use of the sample code, even if they have been */
- /* advised of the possibility of such damages. */
- /* */
- /****************************************************************************/
-
- #include <stdio.h>
- #include "sample03.h"
- size_t _Export nSwaps;
- size_t _Export nCompares;
-
- /* Swap two integers. */
-
- static void swap(int *x, int *y)
- {
- int temp;
- temp = *x;
- *x = *y;
- *y = temp;
- ++nSwaps;
- return ;
- }
-
- /* Compare two integers. */
-
- static int compare(int x, int y)
- {
- ++nCompares;
- return (x-y);
- }
-
- /* Use Bubble Sort to sort an array of integers in increasing order. */
-
- void _Export bubble(int array[], size_t nNumElements)
- {
- size_t i,j; /* array indices */
- nSwaps = nCompares = 0;
- for (i = 0; i < nNumElements-1; ++i) {
- for (j = nNumElements-1; j > i; --j) {
- if (compare(array[j], array[j-1]) < 0)
- swap(&array[j], &array[j-1]);
- }
- }
- return ;
- }
-
- /* Use Insertion Sort to sort an array of integers in increasing order. */
-
- void _Export insertion(int array[], size_t nNumElements)
- {
- size_t i,j; /* array indices */
- nSwaps = nCompares = 0;
- for (i = 1; i < nNumElements; ++i) {
- for (j = i; j && (compare(array[j], array[j-1]) < 0); --j)
- swap(&array[j], &array[j-1]);
- }
- return ;
- }
-
- /* Use Selection Sort to sort an array of integers in increasing order. */
-
- void _Export selection(int array[], size_t nNumElements)
- {
- size_t i,j,lowindex; /* array indices */
- int lowkey; /* temporary storage for lowest key
- value */
- nSwaps = nCompares = 0;
- for (i = 0; i < nNumElements-1; ++i) {
- lowindex = i;
- lowkey = array[i];
- for (j = i+1; j < nNumElements; ++j) {
- if (compare(array[j], lowkey) < 0) {
- lowkey = array[j];
- lowindex = j;
- }
- }
- if (lowindex != i)
- swap(&array[i], &array[lowindex]);
- }
- return ;
- }
-
- /* List the integers in an arrary. */
-
- void _Export list(int array[], size_t nNumElements)
- {
- size_t i;
- for (i = 0; i < nNumElements; ++i)
- printf("%i ", array[i]);
- putchar('\n');
- return ;
- }
-