归并排序模板

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

#define MAXN 100

int board[MAXN];
int result[MAXN];

void Merge(int left,int mid,int right)//治
{
    int a = left;
    int b = mid+1;
    int index = left;
    while(a<=mid || b<=right)
    {
        if(a>mid)result[index++] = board[b++];
        else if(b>right)result[index++] = board[a++];
        else if(board[a]>board[b])result[index++] = board[b++];
        else result[index++] = board[a++];
    }
    for(int i=left ; i<index ; i++)
    {
        board[i] = result[i];
    }
}

void Mysort(int left,int right)//分
{
    if(left<right)
    {
        int mid = (left+right)/2;
        Mysort(left,mid);
        Mysort(mid+1,right);
        Merge(left,mid,right);
    }
}

int main(void)
{
    int N;
    cin>>N;
    for(int i=0 ; i<N ; i++)
    {
        scanf("%d",&board[i]);
    }
    Mysort(0,N-1);
    for(int i=0 ; i<N ; i++)printf("%d ",board[i]);

    return 0;
}
posted @ 2018-01-22 11:02  Assassin_poi君  阅读(102)  评论(0编辑  收藏  举报