之前已经学习了六种常见的排序算法, 包括 插入排序、 归并排序、 快速排序、 希尔排序、 堆排序、 选择排序 。
从总体情况来看 : 插入排序, 选择排序的思路比较简单, 容易完成, 时间复杂度为O(n2)。
而希尔排序、归并排序、 快速排序、 堆排序在思路上有难度, 但是时间上都有了很大的提高, 时间复杂度为 O(n*longn)。
为了对几种排序方法有一个直观的印象, 写了一个小的测试程序对以上六种排序方法进行了一个测试。
下面是测试代码 :
sorts_compare.c :
/***********************************************************/ /* Copyright (C) SA14226214, USTC, 2014-2015 */ /* */ /* FILE NAME : sorsts_compare.c */ /* PRINCIPAL AUTHOR : GaoZhipeng */ /* SUBSYSTEM NAME : sorts_compare */ /* MODULE NAME : insert_sort */ /* LANGUAGE : C */ /* TARGET ENVIRONMENT : ANY */ /* DATE OF FIRST RELEASE : 2015/04/05 */ /* DESCRIPTION : This is a sort program */ /***********************************************************/ /* *Revision log: * *Ceated by GaoZhipeng, 2015/04/05 * */ #include<stdio.h> #include<stdlib.h> #include<time.h> #include"quick_sort.c" #include"merge_sort.c" #include"insert_sort.c" #include"selection_sort.c" #include"shell_sort.c" #include"heap_sort.c" #define MAXSIZE 100000 #define ElementType int #define MAXDATA 65535 int main() { int i; clock_t start, end; double duration; ElementType a[MAXSIZE+1], a0[MAXSIZE+1], a1[MAXSIZE+1], a2[MAXSIZE+1], a3[MAXSIZE+1], a4[MAXSIZE+1], a5[MAXSIZE+1]; srand((unsigned)time(NULL)); for(i=0; i<MAXSIZE; i++) { a[i] = rand()%10000; } a5[0] = MAXDATA; for(i=0; i<MAXSIZE; i++) { a0[i] = a[i]; a1[i] = a[i]; a2[i] = a[i]; a3[i] = a[i]; a4[i] = a[i]; /* a5用于堆排序,下标从1开始 */ a5[i+1] = a[i]; } printf("\n"); /*insert_sort*/ start = clock(); insert_sort(a0, MAXSIZE); end = clock(); duration = (double)(end-start)/CLOCKS_PER_SEC*1000; printf("insert_sort total using : %lf ms\n", duration); /*selection_sort*/ start = clock(); selection_sort(a1, MAXSIZE); end = clock(); duration = (double)(end-start)/CLOCKS_PER_SEC*1000; printf("selection_sort total using : %lf ms\n", duration); /*merge_sort*/ start = clock(); merge_sort(a2, 0, MAXSIZE-1); end = clock(); duration = (double)(end-start)/CLOCKS_PER_SEC*1000; printf("merge_sort total using : %lf ms\n", duration); /*quick_sort*/ start = clock(); quick_sort(a3, 0, MAXSIZE); end = clock(); duration = (double)(end-start)/CLOCKS_PER_SEC*1000; printf("quick_sort total using : %lf ms\n", duration); /*shell_sort*/ start = clock(); shell_sort(a4, MAXSIZE); end = clock(); duration = (double)(end-start)/CLOCKS_PER_SEC*1000; printf("shell_sort total using : %lf ms\n", duration); /*heap_sort*/ start = clock(); heap_sort(a5, MAXSIZE); end = clock(); duration = (double)(end-start)/CLOCKS_PER_SEC*1000; printf("heap_sort total using : %lf ms\n", duration); }