runner% cat sort_select.c #include #include #include #define M 100 void inita(void); void check_sorted(void); void sort_select(int n); int maxind(int); void swap(double *, double *); double a[M]; void main(void) { int starttime, stoptime; /* elapsed time */ int startclock, stopclock; /* CPU time */ srand48((long)time(NULL)); inita(); starttime = time(NULL); startclock = clock(); sort_select(M-1); stoptime = time(NULL); stopclock = clock(); printf("Sorting %i numbers\n", M); printf("Elapsed time: %ld seconds\n", stoptime - starttime); printf("CPU time: %.3f seconds\n", (double)(stopclock - startclock)/1000000.0); check_sorted(); } void sort_select(int n) { int maxi; if (n > 0) { maxi = maxind(n); swap(&a[maxi], &a[n]); sort_select(n-1); } } int maxind(int m) { int maxi; if (m == 0) return m; maxi = maxind(m-1); if (a[m] > a[maxi]) return m; return maxi; } void swap(double *x, double *y) { double z = *x; *x = *y; *y = z; } void inita(void) { int i; for (i = 0; i < M; i++) a[i] = drand48(); } void check_sorted(void) { int sorted = 1; int i; for (i = 0; i < M-1; i++) if (a[i] > a[i+1]) sorted = 0; if(sorted) printf("Array sorted\n"); else printf("*** Array NOT sorted\n"); } runner% sort_select Sorting 100 numbers Elapsed time: 0 seconds CPU time: 0.010 seconds Array sorted runner% sort_select Sorting 500 numbers Elapsed time: 0 seconds CPU time: 0.340 seconds Array sorted runner% sort_select Sorting 1000 numbers Elapsed time: 2 seconds CPU time: 1.520 seconds Array sorted runner% sort_select Sorting 5000 numbers Elapsed time: 41 seconds CPU time: 40.560 seconds Array sorted runner% sort_select Sorting 10000 numbers Elapsed time: 167 seconds CPU time: 165.650 seconds Array sorted runner% sort_select Sorting 20000 numbers Elapsed time: 889 seconds CPU time: 868.100 seconds Array sorted