#if ! defined(INSERTSORT_H)
#define INSERTSORT_H
#include<stdio.h>
#define MAXSIZE 100
typedef int KeyType;//关键字类型用来比较
typedef char InfoType;//其他类型的信息
typedef struct{
KeyType key;//排序用的关键字
InfoType other;//其他附属信息
}RecType;//记录类型
typedef RecType SeqList[MAXSIZE+1];//+1用来使[0]作为哨兵,但是在实际使用中往往不能使[0]作为哨兵
/***********直接插入排序**********
约定:在本次排序中不使用哨兵,直接声明临时变量
基本思路:
1.把待排序的线性表分为有序和无序两部分。
2.从无序里依次取出一个元素往有序区插入到合适部分。
3.直到所有无序区的元素都插入到有序区为止。
*/
void InsertSort(RecType seqlist[],int n){
RecType t;
int i,j;
for(i=1;i<n;i++){
if(seqlist[i].key<seqlist[i-1].key){
j=i;
t=seqlist[i];//暂存
do{
seqlist[j]=seqlist[j-1];
j--;
}while(j-1>=0 && t.key<seqlist[j-1].key);
seqlist[j]=t;
}
}
}
void PrintSeqList(RecType SeqList[],int n){
int i;
for(i=0;i<n;i++){
printf("%2d,%c ",SeqList[i].key,SeqList[i].other);
if(i%10 == 9)
printf("\n");
}
}
void InsertSortTest(){
RecType SeqList[]={{5,'A'},{4,'B'},{3,'C'},{2,'D'},{1,'E'},{6,'F'},{7,'G'},{5,'H'},{2,'I'},{8,'J'},
{9,'K'},{10,'L'},{11,'M'},{12,'N'},{13,'O'},{14,'P'},{1,'Q'},{2,'R'},{3,'S'},{20,'T'}};
int i=0,n=5;
//排序前输出
printf("排序前:\n");
PrintSeqList(SeqList,n);
InsertSort(SeqList,n);
printf("\n排序后:\n");
PrintSeqList(SeqList,n);
printf("\n");
}
/**********希尔排序**********
基本思想:用增量来分割相邻排序比较的粒度,首先用大增量,最后增量用1.
*/
void ShellInsert(RecType list[],int dk,int n){
int i,j;
RecType r;
for(i=dk;i<n;i++){
if(list[i].key<list[i-dk].key){
r=list[i];
j=i;
do{
list[j]=list[j-dk];
j=j-dk;//增量不是1了,增量是DK.交换一次后会变被交换那个和前面的比较
}while(j-dk>=0 && r.key<list[j-dk].key);
list[j]=r;
}
}
}
void ShellSort(RecType R[],int d[],int t,int n){//R[]是线性表,d[]是增量数组,t是增量的个数,n是线性表的个数
int k;
for(k=0;k<t;k++){
ShellInsert(R,d[k],n);
}
}
void ShellSortTest(){
RecType SeqList[]={{5,'A'},{4,'B'},{3,'C'},{2,'D'},{1,'E'},{6,'F'},{7,'G'},{5,'H'},{2,'I'},{8,'J'},
{9,'K'},{10,'L'},{11,'M'},{12,'N'},{13,'O'},{14,'P'},{1,'Q'},{2,'R'},{3,'S'},{20,'T'}};
int i=0,n=10,t=4;
int DK[]={5,3,2,1};
//排序前输出
printf("排序前:\n");
PrintSeqList(SeqList,n);
ShellSort(SeqList,DK,t,n);
printf("\n排序后:\n");
PrintSeqList(SeqList,n);
printf("\n");
}
void main(){
printf("直接插入排序:\n");
InsertSortTest();
printf("希尔排序:\n");
ShellSortTest();
}
#endif
注意文件后缀最好为.c!
希尔排序时j=j-dk,不再是j--,因为增量会变!
最好画一遍执行过程这个比较容易懂!