CS C++

Assignment 10

We know that both selection sort and insertion sort are O(N2) in the worst case, but how do they compare in practice? To make this a fair test, we will use arrays of randomly-generated integers, allow the user to specify the number of elements in the arrays, and average the performance of several trials for each algorithm. To judge performance, we will measure three parameters: the number of comparisons done, the number of swaps performed, and the actual running time of the algorithm.

Write a program that encodes each algorithm as a function. Set up a defined constant specifying the number of trials to be performed for each algorithm. You only need one array (apvector) variable in your main program. You should run at least 10 trials for each sort.

The main program should ask the user for an effective size for the array (use small numbers at first, until you're sure your sort functions work correctly). It should then perform the indicated number of trials for each sort method, generating new elements for the array before each trial. After each series of trials, report the average number of comparisons, average number of swaps, and average running time. Remember to re-initialize the array elements before each trial!

The call random(num) will return a random int between 0 and num - 1. You must include stdlib.h to use the random() function. Choose your value for num so that you'll get a reasonable range of values in your array.

To determine how long it takes for a sort to execute, include time.h and follow this example (the time unit is seconds):

time_t first, second;

double timeDifference;

first = time(NULL); // Get system time

SelectionSort(A);

second = time(NULL); // Get system time again

timeDifference = difftime(second, first);

*******************************************

Here's a better timer mechanism -- I found it after I'd written the assignment. It also allows timing in seconds, but allows for fractions of seconds (which the previous method apparently didn't).

clock_t first, second;

double timeDifference;

first = clock(); // Get system time

SelectionSort(A);

second = clock(); // Get system time again

timeDifference = (second - first) / CLK_TCK;

*******************************************

Please submit a printed copy of your code, plus either your program on disk or a printed sample run.

A program run might look like this:

Enter size of array: 100

Performing selection sort...

Average number of comparisons: 4950

Average number of swaps: 99

Average time elapsed: 0.0033 seconds

Performing insertion sort...

Average number of comparisons: 4901

Average number of swaps: 2479

Average time elapsed: 0.0117 seconds