ernie.WPI.EDU> cat select.C // file select.C, cs2223, D97/98 // // program which selection sorts an array // 02Mar98 NW, First version // global varaibles int compares, swaps; // includes #include "headers.h" // definitions #define NMAX 10000 // prototypes void selection(int, int *); // selection sort an array void shuffle(int, int *); // shuffle the values in an array // main int main () { extern int compares, swaps; int *array = new int[NMAX]; srand(time(NULL)); // seed the random number generator for (int size = 1; size <= NMAX; size *= 10) { cout << endl << "n = " << size << endl; // best case - ascending order for (int i = 0; i < size; i++) array[i] = i + 1; // fill the array in ascending order compares = swaps = 0; selection(size, array); // selection sort cout << " best compares = " << compares << ", swaps = " << swaps << endl; // worst case - descending order for (int i = 0; i < size; i++) array[i] = size - i; // fill the array in descending order compares = swaps = 0; selection(size, array); // selection sort cout << " worst compares = " << compares << ", swaps = " << swaps << endl; } // end for(size) return 0; } // end main() // functions void selection(int n, int *array) // selection sort an array { extern int compares, swaps; int temp; for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) if (compares++, array[j] < array[i]) { swaps++; temp = array[i]; // swap the values array[i] = array[j]; array[j] = temp; } return; } // end selection() void shuffle(int n, int *array) // shuffle the values in an array { for (int i = 0; i < n; i++) { int temp = array[i]; // swap each value with a random one int other = rand() % n; array[i] = array[other]; array[other] = temp; } return; } // end shuffle() // Copyright 1998 Norman Wittels ernie.WPI.EDU> g++ select.C ernie.WPI.EDU> a.out n = 1 best compares = 0, swaps = 0 worst compares = 0, swaps = 0 n = 10 best compares = 45, swaps = 0 worst compares = 45, swaps = 45 n = 100 best compares = 4950, swaps = 0 worst compares = 4950, swaps = 4950 n = 1000 best compares = 499500, swaps = 0 worst compares = 499500, swaps = 499500 n = 10000 best compares = 49995000, swaps = 0 worst compares = 49995000, swaps = 49995000 ernie.WPI.EDU>