数据结构试验2.8
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
2.8内排序
实验2.8.1 实现直接插入排序算法
1.编写一个程序,使用直接插入排序法对以下数据
{75,87,68,92,88,61,77,96,80,72}进行排序。
2. #include
#define MAXE 20 //线性表中最多元素个数
typedefintKeyType;
typedef char InfoType[10];
typedefstruct //记录类型
{
KeyType key; //关键字项
InfoType data; //其他数据项,类型为InfoType
} RecType;
void InsertSort(RecType R[],int n) //对R[0..n-1]按递增有序进行直接插入排序
{
inti,j,k;
RecType temp;
for (i=1;i { temp=R[i]; j=i-1; //从右向左在有序区R[0..i-1]中找R[i]的插入位置 while (j>=0 &&temp.key { R[j+1]=R[j]; //将关键字大于R[i].key的记录后移 j--; } R[j+1]=temp; //在j+1处插入R[i] printf("i=%d,",i); //输出每一趟的排序结果 printf("插入%d,结果为: ",temp); for (k=0;k printf("%3d",R[k].key); printf("\n"); } } void main() { inti,k,n=10; KeyType a[]={75,87,68,92,88,61,77,96,80,72}; RecTypeR[MAXE]; for (i=0;i R[i].key=a[i]; printf("初始关键字: "); //输出初始关键字序列 for (k=0;k printf("%3d",R[k].key); printf("\n"); InsertSort(R,n); printf("最后结果: "); //输出初始关键字序列 for (k=0;k printf("%3d",R[k].key); printf("\n"); } 实验2.8.2 实现希尔插入排序算法 1.编写一个程序,使用希尔插入排序法对以下数据{75,87,68,92,88,61,77,96,80,72}进行排序。 2. #include #define MAXE 20 //线性表中最多元素个数 typedefintKeyType; typedef char InfoType[10]; typedefstruct //记录类型 { KeyType key; //关键字项 InfoType data; //其他数据项,类型为InfoType } RecType; void ShellSort(RecType R[],int n) //希尔排序算法 { inti,j,d,k; RecType temp; d=n/2; //d取初值n/2 while (d>0) { for (i=d;i { j=i-d; while (j>=0 && R[j].key>R[j+d].key) { temp=R[j]; //R[j]与R[j+d]交换 R[j]=R[j+d]; R[j+d]=temp; j=j-d; } } printf("d=%d: ",d); //输出每一趟的排序结果 for (k=0;k printf("%3d",R[k].key); printf("\n"); d=d/2; //递减增量d } } void main() { inti,k,n=10; KeyType a[]={75,87,68,92,88,61,77,96,80,72}; RecTypeR[MAXE]; for (i=0;i R[i].key=a[i]; printf("初始关键字: "); //输出初始关键字序列 for (k=0;k printf("%3d",R[k].key); printf("\n"); ShellSort(R,n); printf("最后结果: "); //输出初始关键字序列 for (k=0;k printf("%3d",R[k].key); printf("\n\n"); } 实验2.8.3 实现冒泡排序算法 1.编写一个程序,使用冒泡排序法对以下数据{75,87,68,92,88,61,77,96,80,72}进行排序。 #include #define MAXE 20 //线性表中最多元素个数 typedefintKeyType; typedef char InfoType[10]; typedefstruct //记录类型 { KeyType key; //关键字项 InfoType data; //其他数据项,类型为InfoType } RecType; void BubbleSort(RecType R[],int n) //冒泡排序算法 { inti,j,k; RecType temp; for (i=0;i { for (j=n-1;j>i;j--) //比较,找出本趟最小关键字的记录 if (R[j].key { temp=R[j]; //R[j]与R[j-1]进行交换,将最小关键字记录前移 R[j]=R[j-1]; R[j-1]=temp; }