在前面我们分别学习了直接插入排序、希尔排序、选择排序、堆排序、冒泡排序、快速排序、归并排序、基数排序下面我们对这些排序的性能、时间复杂度、空间复杂度、稳定性进行归纳比较。
测试代码如下:
// 测试排序的性能对比
void TestOP()
{
srand(time(0));
const int N = 100000;
int* a1 = (int*)malloc(sizeof(int) * N);
int* a2 = (int*)malloc(sizeof(int) * N);
int* a3 = (int*)malloc(sizeof(int) * N);
int* a4 = (int*)malloc(sizeof(int) * N);
int* a5 = (int*)malloc(sizeof(int) * N);
int* a6 = (int*)malloc(sizeof(int) * N);
int* a7 = (int*)malloc(sizeof(int) * N);
int* a8 = (int*)malloc(sizeof(int) * N);
for (int i = 0; i < N; ++i)
{
a1[i] = rand(100000);
a2[i] = a1[i];
a3[i] = a1[i];
a4[i] = a1[i];
a5[i] = a1[i];
a6[i] = a1[i];
a7[i] = a1[i];
a8[i] = a1[i];
}
int begin1 = clock();
InsertSort(a1, N);
int end1 = clock();
int begin2 = clock();
ShellSort(a2, N);
int end2 = clock();
int begin3 = clock();
SelectSort(a3, N);
int end3 = clock();
int begin4 = clock();
HeapSort(a4, N);
int end4 = clock();
int begin5 = clock();
QuickSort(a5, 0, N - 1);
int end5 = clock();
int begin6 = clock();
MergeSort(a6, N);
int end6 = clock();
int begin7 = clock();
RadixSort(a7, N);
int end7 = clock();
int begin8 = clock();
BobbleSort(a8, N);
int end8 = clock();
printf("InsertSort:%d\n", end1 - begin1);
printf("ShellSort:%d\n", end2 - begin2);
printf("SelectSort:%d\n", end3 - begin3);
printf("HeapSort:%d\n", end4 - begin4);
printf("QuickSort:%d\n", end5 - begin5);
printf("MergeSort:%d\n", end6 - begin6);
printf("RadixSort:%d\n", end7 - begin7);
printf("BobbleSort:%d\n", end8 - begin8);
free(a1);
free(a2);
free(a3);
free(a4);
free(a5);
free(a6);
free(a7);
free(a8);
}
第一次比较我们用100000个随机数进行比较,比较的结果如下:
我们可以看出,在无序的情况下,冒泡排序的效率最低,选择次之,直接插入再次之,希尔、堆排、归并、快排、计数是属于同一数量级的,因为基数排序局限于整数排序,因此综合比较,在无序的情况下,快排的效率最高。
第二次比较我们用100000个有序数进行比较,结果如下:
从上图,我们可以看出,在有序的情况下,直接插入、冒泡排序(优化后)的效率最高,计数排序和选择排序的效率不变,其他排序效率有所提高。