Advertisement
cd62131

Sort

Feb 22nd, 2014
362
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.43 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <limits.h>
  5. #define N (1 << 17)
  6. clock_t start, end;
  7.  
  8. void print_time(void) {
  9.   printf("CLOCKS_PER_SEC = %ld, start = %ld, end = %ld\n", CLOCKS_PER_SEC, start, end);
  10.   printf("time = %lf\n\n", (double) (end - start) / CLOCKS_PER_SEC);
  11. }
  12.  
  13. void selection_sort(double *v, int n) {
  14.   int i, j, k;
  15.   double min;
  16.   for (i = 0; i < n - 1; i++) {
  17.     min = v[i]; k = i;
  18.     for (j = i + 1; j < n; j++) if (v[j] < min) { min = v[j]; k = j; }
  19.     v[k] = v[i]; v[i] = min;
  20.   }
  21. }
  22.  
  23. void insertion_sort(double *v, int n) {
  24.   int i, j;
  25.   double t;
  26.   for (i = 1; i < n; i++) {
  27.     t = v[i];
  28.     for (j = i - 1; j >= 0 && v[j] > t; j--) v[j + 1] = v[j];
  29.     v[j + 1] = t;
  30.   }
  31. }
  32.  
  33. void init(double *v, int n) {
  34.   int i;
  35.   for (i = 0; i < N; i++) v[i] = (random() / (double) (RAND_MAX + 1.));
  36. }
  37.  
  38. void print_first_five_elements(double *v) {
  39.   printf("first 5 elements: %lf, %lf, %lf, %lf, %lf\n", v[0], v[1], v[2], v[3], v[4]);
  40. }
  41.  
  42. int main(void) {
  43.   int trial = 3;
  44.   double v[N];
  45.   srandom((unsigned) time(NULL));
  46.   while (trial--) {
  47.     init(v, N);
  48.     puts("Selection Sort:");
  49.     start = clock(); selection_sort(v, N); end = clock();
  50.     print_first_five_elements(v);
  51.     print_time();
  52.  
  53.     init(v, N);
  54.     puts("Insertion Sort:");
  55.     start = clock(); insertion_sort(v, N); end = clock();
  56.     print_first_five_elements(v);
  57.     print_time();
  58.   }
  59.   return 0;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement