常用排序法(希尔排序)

输入

共两行,第一行为一个数N(N≤100000),即排队的总人数,第二行为N个数,即每个人的编号,每个编号均不超过int类型的最大值。

输出

输出排好序的数列,每个数以空格间隙。行尾有空格

样例输入

10
2 1 76 11 4 765 32 56 3 23

样例输出

1 2 3 4 11 23 32 56 76 765 
#include <bits/stdc++.h>
#define ll long long
const int mod=1e9+7;
using namespace std;
int arr[100010];
void shell_sort(int n)
{
    if (arr == NULL)
        return ;
    int h = 1;
    while (h < n/3)
        h = 3*h + 1;
    int i, j, temp;
    while (h >= 1)
    {
        for (i = h; i < n; ++i)
        {
            for (j = i; j >= h && (arr[j] < arr[j-h]); j -= h)
            {
                temp = arr[j];
                arr[j] = arr[j-h];
                arr[j-h] = temp;
            }
        }
        h = h / 3;
    }
}
int main()
{
    int i,j,k,m,n;
    cin>>n;
    for(i=0; i<n; i++)
        cin>>arr[i];
    shell_sort( n);
    for (i=0; i <n-1; ++i)
    {
        printf("%d ", arr[i]);
    }
    printf("%d\n",arr[i]);
    return 0;
}
View Code

猜你喜欢

转载自www.cnblogs.com/nublity/p/9291727.html