文档介绍:1.实验要求
【实验目的】
学****实现、对比各种排序算法,掌握各种排序算法的优劣,以及各种算法使用的情况。
【实验内容】
使用简单数组实现下面各种排序算法,并进行比较。
排序算法:
ﻩﻩ1、插入排序
ﻩﻩ2、希尔排序
3、冒泡排序
4、快速排序
5、简单选择排序
6、堆排序(选作)
7、归并排序(选作)
8、基数排序(选作)
9、其他
要求:
ﻩﻩ1、测试数据分成三类:正序、逆序、随机数据
2、对于这三类数据,比较上述排序算法中关键字的比较次数和移动次数(其中关键字交换计为3次移动)。
3、对于这三类数据,比较上述排序算法中不同算法的执行时间,精确到微秒(选作)
4、对2和3的结果进行分析,验证上述各种算法的时间复杂度
编写测试main()函数测试线性表的正确性。
2。 程序分析
2。1 存储结构
存储结构:数组
r1≤r2≤ … … ≤ri-1 ri ri+1 … … rn
有序区 无序区
图8-1 直接插入排序的基本思想图解
插入到合适位置
关键算法分析
//插入排序
void InsertSort(int r[], int n)
{ﻩ
ﻩint count1=0,count2=0;
ﻩfor (int i=2; i〈n; i++)
ﻩ{
ﻩﻩr[0]=r[i]; //设置哨兵
ﻩﻩfor (int j=i—1; r[0]<r[j]; j——) //寻找插入位置
ﻩﻩﻩr[j+1]=r[j]; //记录后移
ﻩﻩr[j+1]=r[0];
ﻩ count1++;
ﻩﻩcount2++;
ﻩ}
ﻩfor(int k=1;k〈n;k++)
ﻩﻩcout〈〈r[k]<〈” ";
ﻩcout<〈endl;
ﻩcout<〈"比较次数为 "〈<count1<<" 移动次数为 "<<count2<〈endl;
}
//希尔排序
void ShellSort(int r[], int n)
{
ﻩint i;
ﻩint d;
ﻩint j;
ﻩint count1=0,count2=0;
for (d=n/2; d>=1; d=d/2) //以增量为d进行直接插入排序
ﻩ{
ﻩﻩfor (i=d+1; i<n; i++)
ﻩﻩ{
ﻩﻩﻩr[0]=r[i]; //暂存被插入记录
ﻩﻩﻩfor (j=i-d; j〉0 && r[0]<r[j]; j=j—d)
ﻩﻩﻩﻩr[j+d]=r[j]; //记录后移d个位置
ﻩﻩﻩr[j+d]=r[0];
ﻩﻩﻩcount1++;
ﻩﻩcount2=count2+d;
ﻩﻩ}
ﻩﻩcount1++;
ﻩ}
ﻩfor(i=1;i<n;i++)
ﻩcout〈〈r[i]〈〈” ";
ﻩcout<〈endl;
ﻩcout<<"比较次数为 "<<count1<〈” 移动次数为 ”〈<count2<〈endl;
}
r1≤r2≤ … … ≤ri-1 ri ri+1 … … rn
有序区 无序区
图8-1 直接插入排序的基本思想图解
插入到合适位置
//起泡排序
void BubbleSort(int r[], int n)
{
ﻩint temp;
ﻩint exchange;
ﻩint bound;
ﻩint count1=0,count2=0;
exchange=n—1; //第一趟起泡排序的范围是r[1]到r[n]ﻩ
ﻩwhile (exchange) //仅当上一趟排序有记录交换才进行本趟排序
ﻩ{
ﻩﻩbound=exchange;
ﻩﻩexchange=0;
ﻩ for(int j=0;j<bound;j++) ﻩﻩﻩ //一趟起泡排序
ﻩﻩ{
ﻩﻩﻩcount1++;ﻩ ﻩﻩ ﻩﻩﻩ//接下来有一次比较
ﻩﻩﻩif(r[j]>r[j+1])
ﻩﻩﻩ{
ﻩﻩ ﻩtemp=r[j];ﻩﻩﻩﻩﻩﻩﻩ//交换r[j]和r[j+1]
ﻩ ﻩr[j]=r[j+1];
ﻩﻩﻩﻩr[j+1]=temp;
ﻩﻩﻩexchange=j;ﻩﻩﻩﻩﻩﻩﻩ//记录每一次发生记录交换的位置