码迷,mamicode.com
首页 > 编程语言 > 详细

归并排序

时间:2018-05-27 22:11:23      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:using   space   ges   amp   return   归并排序   iostream   pac   show   

 

#include"iostream"
using namespace std;
void show(int *a,int n){
    for(int i = 0;i < n;i++){
        cout<<a[i]<<ends;
    }
    cout<<endl;
}
void merge(int *a,int *b,int l,int center,int rend){
    int lend = center,r = center + 1,l1 = l,i = l;
    while(l <= lend && r <= rend){
        if(a[l] < a[r]){
            b[i++] = a[l++];
        }
        else{
            b[i++] = a[r++];
        }
    }
    while(l <= lend){
        b[i++] = a[l++];
    }
    while(r <= rend){
        b[i++] = a[r++];
    }
    for(int j = l1;j < i;j++){
        a[j] = b[j];
    }
}
void mSort(int *a,int *b,int l,int r){
    if(l < r){
        int center = (l + r) / 2;
        mSort(a,b,l,center);
        mSort(a,b,center + 1,r);
        merge(a,b,l,center,r);    //合并
    }
}
void mergeSort(int *a,int n){
    int *b = new int[n];
    mSort(a,b,0,n - 1);        
    delete []b; 
}

int main(){
    const int n = 10;
    int a[n];
    for(int i = 0;i < n;i++){
        a[i] = n - i;
    }
    show(a,n);
    mergeSort(a,n);
    show(a,n);
    return 0;
}

 

归并排序

标签:using   space   ges   amp   return   归并排序   iostream   pac   show   

原文地址:https://www.cnblogs.com/oleolema/p/9097560.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!