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

归并排序

时间:2019-08-28 11:14:23      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:return   bsp   div   namespace   std   main   iostream   clu   color   

#include <iostream>
using namespace std;
#define maxn 10005
#define inf 999999
int L[maxn], R[maxn],A[maxn],cnt,n;
void merge(int left, int mid, int right) { //合并
    int len1 = mid - left;
    int len2 = right - mid;
    for (int i = 0; i< len1; i++) L[i] = A[left + i];
    for (int i = 0; i<len2; i++) R[i] = A[mid + i];
    L[len1] = R[len2] = inf;
    int i = 0, j = 0;
    for (int k = left; k < right; k++) {
        cnt++;
        if (L[i] <= R[j]) A[k] = L[i++];
        else A[k] = R[j++];
    }
}
void mergesort(int left, int right) {
    if (left + 1 >= right) return;
    int mid = (left + right) / 2;
    //分解
    mergesort(left, mid);
    mergesort(mid, right);
    //合并
    merge(left, mid, right);
}
int main() {
    cnt = 0;
    cin >> n;
    for (int i = 0; i < n; i++) cin >> A[i];
    mergesort(0, n);
    for (int i = 0; i<n; i++) cout << A[i] << " ";
    cout << endl;
    return 0;
}

 

归并排序

标签:return   bsp   div   namespace   std   main   iostream   clu   color   

原文地址:https://www.cnblogs.com/wronin/p/11422353.html

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