分治法-归并排序

#include <iostream>
#include <cstdlib>
#include<cstring>
using namespace std;

#define LQ( a, b)    ((a) <= (b))
#define EQ(a, b)    ((a) == (b))
#define LT(a, b)        ((a) < (b))

void Merge(int a[], int *d, int i, int m, int n)
{
    //将有序的a[i...m],有序的a[m+1...n]归并为有序的d[i...n];
    int j, k, l;
    for(j = m + 1, k = i; i <= m && j <= n; ++k){
        if(LQ(a[i], a[j]))
            d[k] = a[i ++];
        else 
            d[k] = a[j ++];
    }
    if(i <= m)
        for(l = k; l <= n; l ++)
            d[l] = a[i ++];
    if(j <= n)
        for(l = k; l <= n; l ++)
            d[l] = a[j ++];
}
void Msort(int a[], int *b, int s, int t)
{
    //将a[s...t]归并排序为b[s...t]
    int c[105];
    if(s == t)
        b[s] = a[s];
    else{
        int m = (s + t) / 2;        //将a[s...t]平分为a[s...m]和a[m+1...n]
        Msort(a, c, s, m);            //递归的将a[s...m] 归并为有序的c[s...m]
        Msort(a, c, m + 1, t);        //递归的将a[m+1...n]归并为有序的c[m+1...n]
        Merge(c, b, s, m, t);        //将c[s...m]和c[m+1...n]归并到b[s...t]
    }
}

int main()
{
    int N, i, j, ans = 0;
    int E[105], ANS[105];
    scanf("%d", &N);
    for(i = 1; i <= N; i ++){
        scanf("%d", &E[i]);
    }
    Msort(E, ANS, 1, N);
    for(i = 1; i <= N; ++ i)
        cout<<ANS[i]<<" ";
    cout<<endl;
    system("pause");
    return 0;
}
posted on 2012-04-29 15:53  tomctx  阅读(217)  评论(0编辑  收藏  举报