希尔排序的基本是插入排序;
插入排序的步长是1;然而希尔排序的步长是可变的,比如20个数据,以步长为10
进行插排序,在以10-2进行排序依次类推,最后一个步长一定是1。
那么问题来了,为什么要用不同步长来进行插入排序。
因为当一组数据相对有序的化,用插入排序他们每个之间比的次数非常少,
从而提高效率,减轻运算时间。倘若你想想,如果是1个G的数据处理,希尔排序绝对是个不错的选择
程序:
void print(int a[])//打印函数
{
int i;
for(i = 0 ;i < 10;i++)
{
printf("%d ",a[i]);
}
printf("\n");
}
void shell(int a[])//希尔排序
{
int temp;
int i,j,n;
int b[3] = {1,3,5};
int step ;
for (n=2; n>=0; n--)
{
step = b[n];
for ( i = step; i < 10; ++i)
{
temp = a[i];
for (j = i - step; j >=0 ; j-=step)
{
if (a[j] > temp)
{
a[j+step] = a[j];
}
else
{
break;
}
}
a[j+step] = temp;
}
print(a);
}
}
int main()
{
int a[10] = {10,1,8,4,5,7,6,3,2,9};
shell(a);
print(a);
return 0;
}