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

    看了算法导论之后,学了一个小技巧,L1[nL1] = L2[nL2] = ∞,比较时好操作,不用进行边界的讨论


    #include <iostream>
    #include <cstdlib>
    #include <cstring>
    #include <cmath>
    #define inf 0x3f3f3f
    using namespace std;
    
    
    void merge(int a[],int p,int q,int r){
        int nL1 = q-p+1;
        int nL2 = r-q;
        //init
        int *L1 = (int *)malloc(sizeof(int)*nL1+1);
        int *L2 = (int *)malloc(sizeof(int)*nL2+1);
    
        for(int i=0;i<nL1;i++)
            L1[i] = a[p+i];
        for(int i=0;i<nL2;i++)
            L2[i] = a[q+1+i];
        //inf
        L1[nL1] = inf;
        L2[nL2] = inf;
    
        int i=0;
        int j=0;
        for(int k=p;k<=r;k++){
            if(L1[i]<=L2[j]){
                a[k] = L1[i];
                i++;
            }
            else{
                a[k] = L2[j];
                j++;
            }
        }
        //free
        free(L1);
        free(L2);
    }
    
    void mergeSort(int a[],int p,int r){
        if(p>=r)return;
        int q=(p+r)/2;
        mergeSort(a,p,q);
        mergeSort(a,q+1,r);
        merge(a,p,q,r);
    }
    
    ostream& printResult(ostream&cout,int a[],int n){
        for(int i=0;i<n;i++)
            cout<<a[i]<<" ";
        cout<<endl;
        return cout;
    }
    
    int main()
    {
        int n;
        cin>>n;
        int *a =(int *) malloc(sizeof(int)*n);
    
        for(int i=0;i<n;i++)
            a[i] = rand()%1000;
        printResult(cout,a,n);
        mergeSort(a,0,n-1);
        printResult(cout,a,n);
        free(a);
        //cout << "Hello world!" << endl;
        return 0;
    }
    View Code
    在一个谎言的国度,沉默就是英雄
  • 相关阅读:
    MySQL wrapped 连接池
    学习 memcache 心得
    memcachedb 加 memcached engine无法提高 示例检索的查询速度
    memcached+Mysql(主从) php 编程
    动态设置select与radio的默认值
    JSTL 自定义
    坦克大战 Java版
    给超链接加onclick事件
    图片查看器C#
    备份删除还原数据库
  • 原文地址:https://www.cnblogs.com/EdsonLin/p/5321085.html
Copyright © 2011-2022 走看看