/* Test driver for sorting. Written by: G & F Date: 2/98 Brooks/Cole Publishing Company An International Thomson Publishing Company Copyright 1998. All Rights Reserved */ #include #define MAX_ARY_SIZE 15 int main (void) { /* Prototype Declarations */ void bubbleSort (int list[ ], int last) ; /* Local Declarations */ int i ; int ary[ MAX_ARY_SIZE ] = { 89, 72, 3, 15, 21, 57, 61, 44, 19, 98, 5, 77, 39, 59, 61 } ; /* Statements */ printf("Unsorted array: ") ; for (i = 0; i < MAX_ARY_SIZE; i++) printf("%3d", ary[ i ]) ; bubbleSort (ary, MAX_ARY_SIZE - 1) ; printf("\nSorted array: ") ; for (i = 0; i < MAX_ARY_SIZE; i++) printf("%3d", ary[ i ]) ; printf("\n") ; return 0 ; } /* main */ /* =================== bubbleSort ==================== */ /* Sort list using bubble sort. Adjacent elements are compared and exchanged until list is completely ordered. Pre The list must contain at least one item. last contains index to last element in the list. Post List has been rearranged in sequence low to high. */ void bubbleSort (int list [ ], int last) { /* Local Declarations */ int current; int sorted; int walker; int temp; /* Statements */ /* Each iteration is one sort pass */ for (current = 0, sorted = 0; current <= last && !sorted; current++) for (walker = last, sorted = 1; walker > current; walker-- ) if ( list[ walker ] < list[ walker - 1 ] ) /* Any exchange means list is not sorted */ { sorted = 0; temp = list[walker]; list[walker] = list[walker - 1]; list[walker - 1] = temp; } /* if */ return; } /* bubbleSort */ /* Results: Unsorted array: 89 72 3 15 21 57 61 44 19 98 5 77 39 59 61 Sorted array: 3 5 15 19 21 39 44 57 59 61 61 72 77 89 98 */