码迷,mamicode.com
首页 > 其他好文 > 详细

Mergesort

时间:2015-12-24 23:48:23      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:

Mergesort is one of the best-known examples of the unility of the divide-and-conquer paradigm for efficent algorithm design. It is as good as Quicksort.

#include<cstdio>
#include<iostream>
using namespace std;

void Merge( int a[], int first, int mid, int last ) {
    int b[1000], e;
    int i = first;
    int j = mid + 1;
    int len = last - first + 1;
    for( e = 0; e < len; e++ ) {
        if( i == mid + 1 ) b[e] = a[j++];
        else if( j == last +1 ) b[e] = a[i++];
        else if( a[i] < a[j] ) b[e] = a[i++];
        else b[e] = a[j++];
    }
    for( int k = 0; k < len; k++ ) {
        a[first + k] = b[k];
    }
}

void Mergesort( int a[], int first, int last ) {
    int mid = ( first + last ) / 2;
    if( first < last ) {
        Mergesort( a, first, mid );
        Mergesort( a, mid + 1, last );
        Merge( a, first, mid, last);
    }
}

int main()
{
    int n;
    while( cin >> n ) {
        int a[1000];
        for( int i = 0; i < n; i++ ) {
            cin >> a[i];
        }
        Mergesort( a, 0, n - 1 );
        for( int i = 0; i < n; i++) {
            cout << a[i] << ‘ ‘;
        }
        cout << endl;
    }
    return 0;
}

Mergesort

标签:

原文地址:http://www.cnblogs.com/xzrmdx/p/5074607.html

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