- /*
- * Copyright (c)2016,烟台大学计算机与控制工程学院
- * All rights reserved.
- * 文件名称:wu.cpp
- * 作 者:武昊
- * 完成日期:2016年12月15日
- * 版 本 号:v1.0
- *问题描述:采用归并排序、快速排序等高效算法进行排序,当数据元素较少时(如n≤64),经常直接使用直接插入排序算法等高复杂度的算法。这样做,会带来一定的好处,例如归并排序减少分配、回收临时存储区域的频次,快速排序减少递归层次等。
- 试按上面的思路,重新实现归并排序算法。
- 提示1:这一项目需要整合多种排序算法,可以考虑先建设排序算法库,作为我们这门课算法库的收官之作;
- 提示2:本项目旨在获得对于复杂度不同算法的感性认识,由于数据分布特点、计算机运行状态等不同,其结果并不能完全代替对算法复杂度的理论分析;
- 提示3:由于C语言标准提供的时间函数只精确到秒,几种O(nlog2n)级别的算法,在5万条记录的压力下,并不能明显地看出优劣,可以忽略直接插入排序、冒泡排序、直接选择排序这三种相对低效率的算法(以节约时间。若能够忍受他们长时间地运行,请自便),成10倍地加大数据量,然后进行观察。
- *输入描述:无
- *程序输出:测试数据
- */
1.测试用的主控程序——main.cpp
- #include <stdio.h>
- #include <malloc.h>
- #include <stdlib.h>
- #include <time.h>
- #include "sort.h"
- void GetLargeData(RecType *&R, int n)
- {
- srand(time(0));
- R=(RecType*)malloc(sizeof(RecType)*n);
- for(int i=0; i<n; i++)
- R[i].key= rand(); //产生0~RAND_MAX间的数
- printf("生成了%d条记录\n", n);
- }
- //调用某一排序算法完成排序,返回排序用时
- long Sort(RecType *&R, int n, void f(RecType*, int))
- {
- int i;
- long beginTime, endTime;
- RecType *R1=(RecType*)malloc(sizeof(RecType)*n);
- for (i=0;i<n;i++)
- R1[i]=R[i];
- beginTime = time(0);
- f(R1,n);
- endTime = time(0);
- free(R1);
- return endTime-beginTime;
- }
- //调用基数排序算法完成排序,返回排序用时
- long Sort1(RecType *&R, int n)
- {
- long beginTime, endTime;
- RadixRecType *p;
- CreateLink(p,R,n);
- beginTime = time(0);
- RadixSort(p);
- endTime = time(0);
- DestoryLink(p);
- return endTime-beginTime;
- }
- int main()
- {
- RecType *R;
- int n = MaxSize; //测试中, MaxSize取50W
- GetLargeData(R, n);
- printf("各种排序花费时间:\n");
- printf(" 直接插入排序:%ld\n", Sort(R, n, InsertSort));
- printf(" 希尔排序:%ld\n", Sort(R, n, ShellSort));
- printf(" 冒泡排序:%ld\n", Sort(R, n, BubbleSort));
- printf(" 快速排序:%ld\n", Sort(R, n, QuickSort));
- printf(" 直接选择排序:%ld\n", Sort(R, n, SelectSort));
- printf(" 堆排序:%ld\n", Sort(R, n, HeapSort));
- printf(" 归并排序:%ld\n", Sort(R, n, MergeSort));
- printf(" 基数排序:%ld\n", Sort1(R, n));
- free(R);
- return 0;
- }