zoukankan      html  css  js  c++  java
  • 希尔排序

    希尔排序 

      按一定间隔交换元素

    原始希尔排序:

    Dm = [N/2], Dk = [Dk+1/2]

    void Shell_sort(ElementType A[], int N)
    {
        int D, P, i;
        ElementType Tmp;
        for (D = N/2; D > 0; D/= 2) {
            for (P = D; P < N; P++) {
                Tmp = A[P];
                for (i = P; i >= D && A[i-D]>Tmp; i-=D)
                    A[i] = A[i-D];
    
                A[i] = Tmp;
            }
        }
    }

    最坏情况:T = θ(N^2)

    增量序列

    代码:

    #include <iostream>
    typedef long long ElementType;
    using namespace std;
    
    void ShellSort(ElementType A[], int N)
    {  //采用Sedgewick增量序列
        int Si, D, P, i;
        ElementType Tmp;
        //部分增量
        int Sedgewick[] = {929, 505, 209, 41, 19, 5, 1, 0};
    
        for (Si = 0; Sedgewick[Si] >= N; Si++)
            ; //初始增量Sedgewick[Si]不能超过待排序列长度
        for (D = Sedgewick[Si]; D > 0; D = Sedgewick[++Si])
            for (P = D; P < N; P++) {
                Tmp = A[P];
                for (i = P; i >= D && A[i-D] > Tmp; i-= D)
                    A[i] = A[i-D];
                A[i] = Tmp;
            }
    }
    
    int main()
    {
        int N;
        ElementType A[110000];
    
        cin >> N;
        for (int i = 0; i < N; i++)
            cin >> A[i];
        ShellSort(A, N);
        for (int i = 0; i < N-1; i++)
            cout << A[i] << " ";
        cout << A[N-1];
    
        return 0;
    }

    PTA运行结果:

  • 相关阅读:
    teamviewer被识别为商用的解决办法
    PLY调试笔记——待解决的问题
    python中的反射
    类的继承顺序
    面向对象---继承
    类成名和命名空间
    面向对象编程
    模块的初始
    装饰器
    列表推导式,生成器
  • 原文地址:https://www.cnblogs.com/whileskies/p/6864352.html
Copyright © 2011-2022 走看看