第十六周--验证算法(希尔排序)

来源:互联网 发布:仿折800源码 编辑:程序博客网 时间:2024/06/05 11:46
/* *Copyright (c) 2015 烟台大学计算机与控制工程学院 *All right reserved. *标题:数据结构实践——验证算法 希尔排序 *作者:杨珺 *date:2015年12月14日 *版本:V1.0.1 *操作系统:XP *运行环境:VC6.0 *问题描述:用序列{57, 40, 38, 11, 13, 34, 48, 75, 6, 19, 9, 7}作为测试数据, 运行并本周视频中所讲过的算法对应 程序,观察运行结果并深刻领会算法的思路和实现方法*/

#include <stdio.h>#define MaxSize 20typedef int KeyType;    //定义关键字类型typedef char InfoType[10];typedef struct          //记录类型{    KeyType key;        //关键字项    InfoType data;      //其他数据项,类型为InfoType} RecType;              //排序的记录类型定义void ShellSort(RecType R[],int n)   //希尔排序算法{    int i,j,gap;    RecType tmp;    gap=n/2;                //增量置初值    while (gap>0)    {        for (i=gap; i<n; i++) //对所有相隔gap位置的所有元素组进行排序        {            tmp=R[i];            j=i-gap;            while (j>=0 && tmp.key<R[j].key)//对相隔gap位置的元素组进行排序            {                R[j+gap]=R[j];                j=j-gap;            }            R[j+gap]=tmp;            j=j-gap;        }        gap=gap/2;  //减小增量    }}int main(){    int i,n=11;    RecType R[MaxSize];    KeyType a[]= {57, 40, 38, 11, 13, 34, 48, 75, 6, 19, 9, 7};    for (i=0; i<n; i++)        R[i].key=a[i];    printf("排序前:");    for (i=0; i<n; i++)        printf("%d ",R[i].key);    printf("\n");    ShellSort(R,n);    printf("排序后:");    for (i=0; i<n; i++)        printf("%d ",R[i].key);    printf("\n");    return 0;}


运行结果:

 

显示排序过程:

#include <stdio.h>#define MaxSize 20typedef int KeyType;    //定义关键字类型typedef char InfoType[10];typedef struct          //记录类型{    KeyType key;        //关键字项    InfoType data;      //其他数据项,类型为InfoType} RecType;              //排序的记录类型定义void ShellSort(RecType R[],int n)   //希尔排序算法{    int i,j,gap,k;    RecType tmp;    gap=n/2;                //增量置初值    while (gap>0)    {        for (i=gap; i<n; i++) //对所有相隔gap位置的所有元素组进行排序        {            tmp=R[i];            j=i-gap;            while (j>=0 && tmp.key<R[j].key)//对相隔gap位置的元素组进行排序            {                R[j+gap]=R[j];                j=j-gap;            }            R[j+gap]=tmp;            j=j-gap;        }        printf("gap=%d:",gap);        for (k=0; k<n; k++)            printf("%d ",R[k].key);        printf("\n");        gap=gap/2;  //减小增量    }}int main(){    int i,n=11;    RecType R[MaxSize];    KeyType a[]= {57, 40, 38, 11, 13, 34, 48, 75, 6, 19, 9, 7};    for (i=0; i<n; i++)        R[i].key=a[i];    printf("排序前:");    for (i=0; i<n; i++)        printf("%d ",R[i].key);    printf("\n");    ShellSort(R,n);    printf("排序后:");    for (i=0; i<n; i++)        printf("%d ",R[i].key);    printf("\n");    return 0;}


运行结果:

 

0 0