/***************** * sorting_template.c * * template for sorting in C * * For C syntax and libraries, see * https://cs.marlboro.college/courses/spring2016/systems/c_refcard.pdf * * TODO : * * - first, make a copy of this file, as sort_XXX.c * where XXX is your name or an algorithm or whatever; * do your work on that copy. * * - implement and test the "insertion" sorting algorithm. * (i) watch it work for a small n value, printing everything, then * (ii) try it on a larger (10 numbers or so) test case, then * (iii) put in a loop invariant to show explicitly that it works. * * - add loop over multiple values for n, with output performance * (and remove printing the whole thing, of course) * * - invoke from command line with piped output, sending output * to a file for safe keeping , i.e. * * $ gcc sort_XXX.c -o sort_XXX * $ ./sort_XXX > sort_XXX_output.txt * * - profit. ;) * * Jim Mahoney | cs.bennington.college | MIT License | March 2022 *****************/ #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <time.h> double get_secs(){ // return time since program launch clock_t ticks = clock(); double seconds = (double)ticks / (double)CLOCKS_PER_SEC; //printf(" ticks since epoch = %lu ; ", ticks); // debug //printf(" ticks per second = %d \n", CLOCKS_PER_SEC); // . //printf(" seconds = %.6f \n", seconds); // . return seconds; } int* get_randoms(int n){ // return array of n random numbers, randoms[0] to randoms[n-1]. int i; int* randoms = malloc(n * sizeof(int)); for (i=0; i<n; i++) randoms[i] = rand(); return randoms; } void init_randoms(){ // initialize the pseudo random number generator using the system time srand(time(NULL)); } void print_array(int n, int* array){ int i; printf("["); for (i=0; i<n; i++) printf("%d, ", array[i]); printf("]\n"); } void assert_invariant(int i, int* numbers){ // check to see if some loop invaraiant property is true; // print a complaint if it isn't. // YOUR CODE GOES HERE } void sort(int n, int* numbers){ // sort numbers[0] to numbers[n-1] into increasing order, in place. // YOUR CODE GOES HERE // ....... // ........ // ... including using some sort of loop invariant // // } int main(){ int* randoms; int n = 4; double start, stop; start = get_secs(); init_randoms(); printf(" -- sorting -- \n"); printf(" (max int is %d ;", INT_MAX); printf(" max random is %d ;", RAND_MAX); printf(" a random is %d.) \n\n", rand()); randoms = get_randoms(n); printf("initial numbers: \n "); print_array(n, randoms); printf("\n"); sort(n, randoms); printf("sorted numbers: \n "); print_array(n, randoms); printf("\n"); stop = get_secs(); printf(" elapsed time is %.8f seconds \n", stop - start); return 0; }