main.cpp:
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;
}
2.头文件 —— sort.h
#ifndef SORT_H_INCLUDED
#define SORT_H_INCLUDED
#define MaxSize 50000 //最多的数据,取5万,只测试快速算法,可以往大调整
//下面的符号常量和结构体针对基数排序
#define Radix 10 //基数的取值
#define Digits 10 //关键字位数
typedef int KeyType; //定义关键字类型
typedef char InfoType[10];
typedef struct //记录类型
{
KeyType key; //关键字项
InfoType data; //其他数据项,类型为InfoType
} RecType; //排序的记录类型定义
typedef struct node
{
KeyType data; //记录的关键字,同算法讲解中有差别
struct node *next;
} RadixRecType;
void InsertSort(RecType R[],int n); //直接插入排序
void ShellSort(RecType R[],int n); //希尔排序算法
void BubbleSort(RecType R[],int n); //冒泡排序
void QuickSort(RecType R[],int n); //快速排序
void SelectSort(RecType R[],int n); //直接选择排序
void HeapSort(RecType R[],int n); //堆排序
void MergeSort(RecType R[],int n); //归并排序
//下面函数支持基数排序
void CreateLink(RadixRecType *&p,RecType R[],int n); //创建基数排序用的链表
void DestoryLink(RadixRecType *&p); //释放基数排序用的链表
void RadixSort(RadixRecType *&p); //基数排序
#endif // SORT_H_INCLUDED
3.算法的实现—— sort.cpp
#include "sort.h"
#include <malloc.h>
//1. 对R[0..n-1]按递增有序进行直接插入排序
void InsertSort(RecType R[],int n)
{
int i,j;
RecType tmp;
for (i=1; i<n; i++)
{
tmp=R[i];
j=i-1; //从右向左在有序区R[0..i-1]中找R[i]的插入位置
while (j>=0 && tmp.key<R[j].key)
{
R[j+1]=R[j]; //将关键字大于R[i].key的记录后移
j--;
}
R[j+1]=tmp; //在j+1处插入R[i]
}
}
运行结果: