1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| #include <stdio.h> #include <stdlib.h> #include <time.h> #define MAXSIZE 10000 void swap(int *a, int *b){int tmp;tmp=*a;*a = *b;*b = tmp;} void rand_Array(int Array[]){for (int i = 0; i < MAXSIZE; i++)Array[i] = rand();} void selection_sort(int a[],int l, int r) { for (int i = l; i <= r; i++) { int min = i; for (int j = i + 1; j <= r; j++) if (a[j] < a[min]) min = j; swap(&a[min], &a[i]); } } void insertion_sort(int a[],int l, int r) { for (int i = l + 1; i <= r; i++) { int key = a[i]; int j = i - 1; while ((j >= 0) && (key < a[j])) { a[j + 1] = a[j]; j--; } a[j + 1] = key; } } void bubble_sort(int a[],int l,int r) { for (int i = l; i <= r; i++) for (int j = l; j <= r - i; j++) if (a[j] > a[j + 1]) swap(&a[j], &a[j+1]); } void quick_sort(int a[],int l, int r) { int i = l, j = r, mid = a[(l + r) / 2]; do { while (a[i] < mid)i++; while (a[j] > mid)j--; if (i <= j) { swap(&a[i], &a[j]); i++; j--; } } while (i <= j); if (l < j) quick_sort(a,l,j); if (i < r) quick_sort(a,i,r); } int main() { int Array[MAXSIZE]; clock_t start,end;
rand_Array(Array); start=clock(); insertion_sort(Array,0,MAXSIZE-1); end=clock(); printf("insertion_sort runs in %lf seconds\n",(double)(end-start)/CLOCKS_PER_SEC);
rand_Array(Array); start=clock(); selection_sort(Array,0,MAXSIZE-1); end=clock(); printf("selection_sort runs in %lf seconds\n",(double)(end-start)/CLOCKS_PER_SEC);
rand_Array(Array); start=clock(); bubble_sort(Array,0,MAXSIZE-1); end=clock(); printf("bubble_sort runs in %lf seconds\n",(double)(end-start)/CLOCKS_PER_SEC);
rand_Array(Array); start=clock(); quick_sort(Array,0,MAXSIZE-1); end=clock(); printf("quick_sort runs in %lf seconds\n",(double)(end-start)/CLOCKS_PER_SEC); }
|