介绍了2种希尔排序的实现方式。
#include <stdio.h>
// 交换函数
void swap (int a[], int i, int j)
{
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
// 打印数组
void printA (int *a, int len)
{
int i;
for (i = 0; i < len; i++)
{
printf ("%4d", a[i]);
}
printf ("\n");
}
// 希尔排序
int main1()
{
int a[10] = {9,6,8,0,3,5,2,4,7,1};
int len = sizeof(a) / sizeof(a[0]);
int i,j,get;
int d = len; // d代表每一次的步长
do
{
d = d / 3 + 1;
for (i = d; i < len; i++)
{
get = a[i];
j = i - d;
while (j >= 0 && a[j] > get)
{
a[j+d] = a[j];
j -= d;
}
a[j+d] = get;
}
}while (d > 1);
printA (a, len);
return 0;
}
int main()
{
int a[10] = {9,6,8,0,3,5,2,4,7,1};
int len = sizeof(a) / sizeof(a[0]);
int i,j,get;
int d = 0; // d代表每一次的步长
while (d < len)
{
d = d * 3 + 1; // 0 1 4 13
}
while (d >= 1)
{
for (i = d; i < len; i++)
{
get = a[i];
j = i - d;
while (j >= 0 && a[j] > get)
{
a[j+d] = a[j];
j -= d;
}
a[j+d] = get;
}
d = (d-1) / 3; // 4 1 0
}
printA (a, len);
return 0;
}