zoukankan      html  css  js  c++  java
  • 合并排序

     

    理解参照 网站 https://blog.csdn.net/li528405176/article/details/86615003

    代码参考网址 https://blog.csdn.net/feierxiaoyezi/article/details/79998060?depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-5&utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-5

    合并排序的理解

    动图理解非常好懂

     

    //date:2020.4.21
    #include <bits/stdc++.h>
    using namespace std;
    void merge(int A[],int l,int m,int r)
    {
        int left=m-l+1;
        int right=r-m;
        int L[left+1];
        int R[right+1];
        for(int i=0; i<left; i++)
        {
            L[i]=A[l+i];
        }
        for(int i=0; i<right; i++)
        {
            R[i]=A[m+i+1];
        }
        L[left]=1000;//假设100是无穷大的数
        R[right]=1000;//这两句话可以让最后一个数字进入,
        //比如 35 28 在合并的时候 8还没进去,此i=1,j=2,
        //此时j=2,R[2]=1000一个较大的数,使最后一个8能进去
        //这也是定义L[left+1],R[right+1]的意义
        int i=0,j=0;
        for(int q=l; q<=r; q++)
        {
            if(L[i]<=R[j])
            {
                A[q]=L[i];
                i++;
            }
            else
            {
                A[q]=R[j];
                j++;
            }
        }
        for(int i=0; i<8; i++)
            cout << A[i] <<" ";
        cout<<endl;
    }
    void mergesort(int A[],int l,int r)
    {
        int mid;
        if(r>l)
        {
            mid=floor((l+r)/2);
            mergesort(A,l,mid);
            mergesort(A,mid+1,r);
            merge(A,l,mid,r);
        }
    }
    int main()
    {
        int A[]= {8,3,5,2,4,1,9,6};
        mergesort(A,0,7);
        cout<<"the result of mergesort is:"<<endl;
        for(int i=0; i<sizeof(A)/sizeof(A[0]); i++)
            cout << A[i] <<" ";
        return 0;
    }
    

      输出结果

    3 8 5 2 4 1 9 6
    3 8 2 5 4 1 9 6
    2 3 5 8 4 1 9 6
    2 3 5 8 1 4 9 6
    2 3 5 8 1 4 6 9
    2 3 5 8 1 4 6 9
    1 2 3 4 5 6 8 9
    the result of mergesort is:
    1 2 3 4 5 6 8 9
    

      

  • 相关阅读:
    输入框联想
    SyntaxError: missing ; before statement 错误的解决
    Oracle数据库DECODE函数的使用.
    MySQL ----命令总结!
    个介!
    递归函数
    闭包函数与装饰器
    函数对象
    力扣题
    函数基础
  • 原文地址:https://www.cnblogs.com/someonezero/p/12743165.html
Copyright © 2011-2022 走看看