希尔排序算法第一次实现了复杂度小于O(n2)的算法, 使得以后有更好的算法的出现.
1. 希尔排序算法的实现
1.seqlist.h
# define MAXSIZE 10
typedef struct
{
int r[MAXSIZE + 1];
int length;
}SqList;
void ShellSort(SqList *l);
# endif
2.seqlist.c
# include <stdio.h>
# include <stdlib.h>
# include "seqlist.h"
void swap(SqList *s,int i, int j)
{
int temp;
temp = s->r[i];
s->r[i] = s->r[j];
s->r[j] = temp;
}
void PrintList(SqList l)
{
int i;
for (i=1; i < l.length; ++i)
printf_s("%5d", l.r[i]);
printf_s("%5d", l.r[i]);
printf_s("\n");
}
void ShellSort(SqList *l)
{
int i, j;
int increment = l->length;
do
{
increment = increment/3 + 1;
for (i=increment+1; i<=l->length; ++i)
{
if (l->r[i] < l->r[i-increment])
{
l->r[0] = l->r[i];
for(j=i-increment; j>0 && l->r[0]<l->r[j]; j-=increment)
l->r[j+increment] = l->r[j];
l->r[j+increment] = l->r[0];
}
}
}while (increment > 1);
}
3.main.c
# include "seqlist.h"
# include <stdio.h>
# include <stdlib.h>
# define N 10
void main()
{
int i;
int d[N] = {100, 50, 10, 90, 30, 70, 40, 80, 60, 20};
SqList l0;
for(i=0; i<N; ++i)
{
l0.r[i+1] = d[i];
}
l0.length = N;
printf_s("The value which before sort is:\n");
PrintList(l0);
ShellSort(&l0);
printf_s("The value which after sort is:\n");
PrintList(l0);
}