这里为了不修改我之前的文章,重新贴一下之前的代码
//selectSort && quickSort comparison #include <sys/time.h> #include <time.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <unistd.h> void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } int partition(int a[], int idxLeft, int idxRight, int idxPivot) { int i, idxCur = idxLeft; int pivot = a[idxPivot]; swap(&a[idxPivot], &a[idxRight]); for(i = idxLeft; i < idxRight; i++){ if(a[i] <= pivot){ swap(&a[i], &a[idxCur]); idxCur++; } } swap(&a[idxCur], &a[idxRight]); return idxCur; } void quicksort(int a[], int idxLeft, int idxRight) { if(idxLeft >= idxRight){ return; } int idxPivot; idxPivot = partition(a, idxLeft, idxRight, (idxRight + idxLeft)/2); quicksort(a, idxLeft, idxPivot - 1); quicksort(a, idxPivot + 1, idxRight); } void selectSort(int a[], int size) { int i, j, aux;//auxiliary for(i = 0; i< size - 1; i++){ aux = i; for(j = i + 1; j < size; j++){ if(a[aux] > a[j]){ aux = j; } } if(i != aux){ swap(&a[i], &a[aux]); } } } #define DEBUG_SORTx int main(int argc, char **argv) { if(argc != 2){ printf("\tusage : ./test SIZE\n"); return -1; } //the larger the SIZE, the better of the quick sort int SIZE = atoi(argv[1]); int a[SIZE], i, b[SIZE]; struct timeval tv1, tv2, tv3; srand(time(NULL)^getpid()); for(i = 0; i < SIZE; i++){ a[i] = rand() % 1000; } a[0] = 73, a[1] = 97, a[2]= 26; memcpy(b, a, sizeof(a)); int size = sizeof(a)/sizeof(int); gettimeofday(&tv1, NULL); //(2) selectSort(a, size); gettimeofday(&tv2, NULL); printf("s : %.3lf ms\n", (tv2.tv_usec - tv1.tv_usec) * 1.0 / 1000 + (tv2.tv_sec - tv1.tv_sec) * 1000); quicksort(b, 0, size - 1); gettimeofday(&tv3, NULL); printf("q : %.3lf ms\n", (tv3.tv_usec - tv2.tv_usec) * 1.0 / 1000 + (tv3.tv_sec - tv2.tv_sec) * 1000); #ifdef DEBUG_SORT for(i = 0; i< size; i++){ printf("%d\t", a[i]); } printf("\n"); for(i = 0; i< size; i++){ printf("%d\t", b[i]); } printf("\n"); #endif return 0; }
运行./out 100000
输出结果:
s : 11630.885 ms
q : 42.877 ms
10万条数据排序,二者性能已经相当明显。选择排序使用了11.6s,而快速排序只用了42.9ms
时间: 2024-11-05 08:43:59