数据结构实验之排序六:希尔排序
Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic
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
Hint
Author
xam
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int a[1211211];
void shellsort(int n)
{
for(int gap = n/2; gap>=1; gap/=2)
{
for(int i=0; i<gap; i++)
{
for(int j=gap+i; j<n; j+=gap)
{
if(a[j-gap]>a[j])
{
int temp = a[j];
int index = j-gap;
while(index>=0&&a[index]>temp)
{
a[index+gap] = a[index];
index -= gap;
}
a[index+gap] = temp;
}
}
}
if(gap==n/2)
{
for(int i=0; i<n; i++)
printf("%d%c", a[i], i==n-1?'\n':' ');
}
if(gap==1)
{
for(int i=0; i<n; i++)
printf("%d%c", a[i], i==n-1?'\n':' ');
}
}
}
int main()
{
int n;
while(~scanf("%d", &n))
{
for(int i=0; i<n; i++)
scanf("%d", &a[i]);
shellsort(n);
}
return 0;
}