问题及代码:
/*
copyright (t) 2016,烟台大学计算机学院
*All rights reserved.
*文件名称:1.cpp
*作者:常锐
*完成日期:2016年12月8日
*版本号:v1.0
*问题描述:请用希尔排序算法,完成序列{57, 40, 38, 11, 13, 34, 48, 75, 6, 19, 9, 7}的排序
*输入描述:无
*程序输出:测试结果
*/
#include <stdio.h>
#define MaxSize 1000
typedef int KeyType;
typedef struct
{
KeyType key;
//InfoType data;
} 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=10;
RecType R[MaxSize];
KeyType a[]= {0,9,2,1,6,5,4,8,7,3};
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;
}
运行结果:
知识点总结:
内部排序-希尔排序算法
心得体会:
希尔排序算法思想:分组排序,取增量,然后在各组内进行直接插入排序。