//希尔排序(Shell Sort)是插入排序的一种。因D.L.Shell于1959年提出而得名。
#include<iostream>
using namespace std;
void shell_insert(int num[],int n,int h,int a)
{
int i,j,temp;
for(i=h;i<n;i++)
{
if(num[i]<num[i-h])
{
temp=num[i];
num[i]=num[i-h];
//==========================除了比较num[i]和前面的num[i-h]之外,还得继续向前比较
for( j=i-h*2; j>=0 && temp<num[j]; j-=h )
num[j+h]=num[j];
num[j+h]=temp;
}
//===========================每次交换后输出,追踪排序的过程
cout<<"第"<<a<<"回,i="<<i<<" ";
for(int k=0;k<=i;k++)
cout<<num[k]<<" ";
cout<<endl;
}
}
void shell_sort(int num[],int n)
{
int h=0;
int a=0;
while(h*3+1<=n) //h是间距
h=h*3+1;
while(h>0)
{
shell_insert(num,n,h,a); //此处的a是追踪排序过程的,不要弄错
h=(h-1)/3;
a++;
cout<<endl;
}
}
int main()
{
FILE*fin=fopen("8.1.2.txt","r");
int num[80],i=0;
while(fscanf(fin,"%d",&num[i])!=EOF)
i++;
int n=i;
shell_sort(num,n);
for(i=0;i<n;i++)
{
if(i%5==0)
cout<<endl;
cout<<num[i]<<" ";
}
cout<<endl;
fclose(fin);
return 0;
}