zoukankan      html  css  js  c++  java
  • 算法探索——归并排序算法

    向博客“白话经典算法系列之五 归并排序的实现”学习(https://www.cnblogs.com/lcchuguo/p/4533302.html)

    step1: 合并两个有序数列

    //合并有序数列a[]和b[]
    void TryMergeArray(int a[], int b[], int la, int lb, int c[]){
        int i,j,k;
        i=j=k=0;
        while(i<la && j<lb){
            if(a[i] < b[j])
                c[k++] = a[i++];
            else
                c[k++] = b[j++];
        }
        while(i<la)
            c[k++] = a[i++];
        while(j<lb)
            c[k++] = b[j++];
    }

    step2: 合并一个序列中的两个有序子串

    //合并有序数列a[first,...,mid]和a[mid+1,...,last]
    void MergeArray(int a[], int first, int mid, int last, int temp[]){
        int i=first, j=mid+1, 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(int l=0; l<k; ++l)
            a[first+l] = temp[l];
    }

    step3: 用二分法将一个长数列拆分成两个短数列,分别排序,再合并

    这一步递归调用自身函数,即拆分数列直至长度为一,而后排序归并

    //归并排序a[first,...,last]
    void MergeSortPart(int a[], int first, int last, int temp[]){
        if(first < last){
            int mid = (first + last) / 2;
            MergeSortPart(a, first, mid, temp);//左边排序
            MergeSortPart(a, mid+1, last, temp);//右边排序
            MergeArray(a, first, mid, last, temp);//合并有序数列
        }
    }

    用这张图更好理解

    step4: 最终函数,非常简洁

    //归并排序
    bool MergeSort(int a[], int n){
        if(n == 0)
            return false;
        int *p = new int[n];
        MergeSortPart(a, 0, n-1, p);
        delete []p;
        return true;
    }
  • 相关阅读:
    笨蛋的厄运
    模仿写了一个摸鱼应用解决原作者的问题
    retain和copy还有assign的区别
    分析与理解通知消息WM_NOTIFY
    备忘录
    数据结构C++模板实现之单向链表
    服务器(VPS合租)
    复制构造,赋值操作符,const重要性
    Windows 注册表操作简介
    窗口类封装之窗口对象消息处理的映射方法(1)
  • 原文地址:https://www.cnblogs.com/tanshiyin-20001111/p/11525781.html
Copyright © 2011-2022 走看看