#include <stdio.h>
#include <stdio.h>
#include <time.h>
#define SIZE 10
void ShellSort(int *a,int len)
{
int i,j,h;
int r,temp;
int x=0;
for (r=len/2;r>=1;r/=2)//先取n/2个序列,再取n/4个序列,n/8个序列。。。
{
for (i=r;i<len;i++)
{
//利用插入排序进行局部排序,插入排序的原理是先对n个数的前两个排序,在将第3个插入前两个数,第4个插入前三个数。。。
temp=a[i];//将要插入的数放在temp中,找到适当的位置后插入
j=i-r;
while (j>=0&&temp<a[j])//temp比前面一个位置上的数小的话,前面的数就要后移
{
a[j+r]=a[j];//后移
j-=r;//找到前面一个位置上的数
}
a[j+r]=temp;//temp插进这个位置
}
x++;
printf("输出第%d步排序结果:",x);
for (h=0;h<len;h++)
{
printf("%d ",a[h]);
}
printf("\n");
}
}
void main()
{
int i,arr[SIZE];
srand(time(NULL));
for(i=0;i<SIZE;i++)
{
arr[i]=rand()%100+100;
}
printf("排序前:\n");
for (i=0;i<SIZE;i++)
{
printf("%d ",arr[i]);
}
printf("\n");
ShellSort(arr,SIZE);
printf("排序后:\n");
for (i=0;i<SIZE;i++)
{
printf("%d ",arr[i]);
}
printf("\n");
}
希尔排序用到了分治算法思想,实际上就是将一堆数划分为若干个序列,然后对序列分别进行排序。