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
    

      

  • 相关阅读:
    Java并发编程(二)线程任务的中断(interrupt)
    Java并发编程(一) 两种实现多线程的方法(Thread,Runnable)
    青蛙跳台阶(Fibonacci数列)
    旋转数组的最小值
    用两个栈实现队列
    重建二叉树
    二维数组中的查找
    Lab 3-1
    Lab 1-4
    Lab 1-3
  • 原文地址:https://www.cnblogs.com/someonezero/p/12743165.html
Copyright © 2011-2022 走看看