zoukankan      html  css  js  c++  java
  • 排序算法复习—归并排序


    基本思路就是将数组分成二组A,B,各自再分成二组。依次类推,当分出来的小组只有一个数据时,可以认为这个小组组内已经达到了有序,然后有序的合并相邻的二个小组就可以了。这样通过先递归的分解数列,再合并数列就完成了归并排序。

    void mergearray(int a[],int first,int mid,int last,int temp[])
    {
        int i=first,j=mid+1;
        int k=0;
        while(i<=mid && j<=last)
        {
            if(a[i] <= a[j])
                temp[k++]=a[i++];
            else
                temp[k++]=a[j++];
    
        }
        while(i<=mid)
            temp[k++]=a[i++];
    
        while(j<=last)
            temp[k++]=a[j++];
    
        for(i=0;i<k;i++)
            a[first+i]=temp[i];
    
    }
    void mergesort(int a[],int first,int last,int temp[])
    {
        if(first<last)
        {
            int mid=(first+last)/2;
            mergesort(a,first,mid,temp);   //使first到mid有序
            mergesort(a,mid+1,last,temp);  //使mid+1到last有序
            mergearray(a,first,mid,last,temp); //合并二个有序数列
            
        }
    }
    int _tmain(int argc, _TCHAR* argv[])
    {
        int a[]={8,22,34,3,14,55,7,43,56,67,31,99};
        int n=sizeof(a)/sizeof(int);
        int *p = new int[n];
        if(p == NULL)
            return -1;
        mergesort(a,0,n-1,p);
        delete[] p;
    
    
        for(int k=0;k<n;k++)
        {
            cout<<a[k]<<",";
        }
        int aa;
        cin>>aa;
        return 0;
    }

    代码出自 MoreWindows Blog   算法讲解的比较到位

  • 相关阅读:
    WebStorm 2017.1.2 汉化破解
    gulp实时刷新页面
    图片转base64
    swiper使用案例一
    js生成GUID
    css实现0.5像素
    mac上搭建appium+IOS自动化测试环境(二)
    6. 使用antd pro构建web页面
    5. 使用Flask蓝图(blueprint)
    4. 为HelloWorld添加日志
  • 原文地址:https://www.cnblogs.com/supercell/p/3622665.html
Copyright © 2011-2022 走看看