• 归并排序


    归并排序

    归并的排序的核心在于合并,递归到底一个数字自然有序

    python

    def merge(A, p, q, r):
        L = A[p:q+1]
        R = A[q+1:r+1]
        L.append(float("inf"))
        R.append(float("inf"))
        i = 0
        j = 0
        k = p
        while k <= r:
            if L[i] <= R[j]:
                A[k] = L[i]
                i = i + 1
                k = k + 1
            else:
                A[k] = R[j]
                j = j + 1
                k = k + 1
    def merge_sort(A, p, r):
        if p < r:
            q = (p + r) // 2
            merge_sort(A,p,q)
            merge_sort(A,q+1,r)
            merge(A,p,q,r)
    
    if __name__ == "__main__":
        A = [5, 2, 4, 7, 1, 3, 2, 6]
        print("排序前", A)
        merge_sort(A, 0, 7)
        print("排序后", A)
    

    c++

    #include <iostream>
    #include <limits.h>
    using namespace std;
    
    void merge(int A[], int p, int q, int r)
    {
        int n1 = q - p + 1;
        int n2 = r - q;
        int L[n1+1];
        int R[n2+1];
        L[n1] = INT_MAX;
        R[n2] = INT_MAX;
        for (int i = 0; i < n1; i++)
        {
            L[i] = A[p+i];
        }
        for (int i = 0; i < n2; i++)
        {
            R[i] = A[q+i+1];
        }
        int i = 0;
        int j = 0;
        for (int k = p; k <= r; k++)
        {
            if (L[i] <= R[j])
            {
                A[k] = L[i];
                i = i + 1;
            }
            else
            {
                A[k] = R[j];
                j = j + 1;
            }
        }
    }
    
    void merge_sort(int A[], int p, int r)
    {
        if (p < r)
        {
            int q = (p + r) / 2;
            merge_sort(A, p, q);
            merge_sort(A, q+1, r);
            merge(A, p, q, r);
        }
    }
    
    int main()
    {
        int A[] = {5, 2, 4, 7, 1, 3, 2, 6};
        cout << "排序前 ";
        for(int i = 0; i < 8; i++)
        {
            cout << A[i] << " ";
        }
        cout << endl;
        merge_sort(A, 0, 7);
        cout << "排序后 ";
        for(int i = 0; i < 8; i++)
        {
            cout << A[i] << " ";
        }
        return 0;
    }
    

    算法分析

    合并的时间复杂度为 $ heta(n)$
    归并时间复杂度 $T(n)=egin{cases}
    heta(1) & n=1
    2T(n/2) + heta(n) & n>1
    end{cases}$
    通过求解递归树,每一层为$cn$, 共$nlgn+1$层,故时间复杂度为$ heta(nlgn)$
    在30个元素以上,归并排序由于插入排序`

  • 相关阅读:
    css mix-blend-mode 混合模式
    vue-slicksort拖拽组件
    123457123457#0#-----com.yuming.TruckCarRun01--前拼后广--大卡车游戏cym
    123457123457#0#---------com.ppGame.SeaPuzzleGame73--前拼后广--宝宝海洋拼图pp
    123457123456#0#-----com.yuming.FromPuzzleGame01--前拼后广--宝宝农场拼图cym
    iOS中NSTimer的使用
    ios排序NSArray(数字.字符串)
    Github排名靠前的iOS库
    mac命令强制清空废纸篓
    我的iOS动画01
  • 原文地址:https://www.cnblogs.com/vito_wang/p/10803213.html
Copyright © 2020-2023  润新知