Problem Description
我们已经学习了各种排序方法,知道在不同的情况下要选择不同的排序算法,以期达到最好的排序效率;对于待排序数据来说,若数据基本有序且记录较少时, 直接插入排序的效率是非常好的,希尔排序就是针对一组基本有序的少量数据记录进行排序的高效算法。你的任务是对于给定的数据进行希尔排序,其中增量dk=n/(2^k)(k=1,2,3……)
Input
连续输入多组数据,每组输入数据的第一行给出一个正整数N(N <= 10000),随后连续给出N个整数表示待排序关键字,数字间以空格分隔。
Output
输出dk=n/2和dk=1时的结果。
Example Input
10 10 9 8 7 6 5 4 3 2 1 10 -5 9 7 -11 37 -22 99 288 33 66
Example Output
5 4 3 2 1 10 9 8 7 6 1 2 3 4 5 6 7 8 9 10 -22 9 7 -11 37 -5 99 288 33 66 -22 -11 -5 7 9 33 37 66 99 288
#include <iostream>
#include <stdio.h>
using namespace std;
int a[10020], b[10020];
void shell(int a[], int n, int dk)
{
int i, j;
for(i = 2; i <= n; i++)
{
if(a[i] < a[i - dk])
{
a[0] = a[i];
for(j = i - dk; j > 0 && a[j] > a[0]; j -= dk)
{
a[j + dk] = a[j];
}
a[j + dk] = a[0];
}
}
}
int main()
{
int n, i;
while(cin>>n)
{
for(i = 1; i <= n; i++)
{
cin>>a[i];
b[i] = a[i];
}
shell(a, n, n / 2);
shell(b, n, 1);
for(i = 1; i < n; i++)
cout<<a[i]<<" ";
cout<<a[i]<<endl;
for(i = 1; i < n; i++)
cout<<b[i]<<" ";
cout<<b[i]<<endl;
}
return 0;
}