zoukankan      html  css  js  c++  java
  • 归并排序模板

    #include <iostream>
    #include <cstdio>
    
    const int MAXN = 100002;
    using namespace std;
    
    int array[MAXN], array2[MAXN];
    void Merge(int low, int high){
        int i = low;
        int mid = (low + high)/2;
        int j = mid+1;
        int k = low;
    
        while(i <= mid && j <= high){//比较两个数组,把其中最小的加进去
            if(array[i] <= array[j]){
                array2[k++] = array[i++];
            }else {
                array2[k++] = array[j++];
            }
        }
        while(i <= mid){//如果前者没有加完, 则把前面的数组里的数加进去
            array2[k++] = array[i++];
        }
        while(j <= high){//意义同上, 两者只会有一个数组有空余
            array2[k++] = array[j++];
        }
        for(int s = low; s <= high; s++){
            array[s] = array2[s];
        }
    }
    void MSort(int low, int high){//分治
        if(low == high){
            array2[low] = array[low];
        }else {
        int mid = (low + high) /2;
        MSort(low, mid);
        MSort(mid+1, high);
        Merge(low, high);//合并
        }
    }
    int main()
    {
        for(int i = 0; i < 10; i++){
            array[i] = 10 - i;
            printf("%d ", array[i]);
        }
        printf("
    ");
        MSort(0, 9);
        for(int i = 0; i < 10; i++){
            printf("%d ", array[i]);
        }
        return 0;
    }
  • 相关阅读:
    java冒泡算法
    java时间操作
    Java重写构造方法
    正则Sub用法
    Python正则反向引用
    Django发送邮件
    Django导出excel
    Nginx编译安装
    年薪20万Python工程师进阶(7):Python资源大全,让你相见恨晚的Python库
    Go语言学习笔记
  • 原文地址:https://www.cnblogs.com/cshg/p/5723251.html
Copyright © 2011-2022 走看看