归并排序

来源:互联网 发布:知网 高质量 知乎 编辑:程序博客网 时间:2024/06/14 00:16
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include<string.h>
#define maxn 100
#define mem(a,b) memset(a,b,sizeof(a));
using namespace std;
int a[105];int n;int temp[100];
void   memger(int a[],int first,int mid,int last,int temp[])
{
    int i=first;int j=mid+1;
    int k=0;
    while(i<=mid&&j<=last)
    {
        if(a[i]<=a[j])
        {
            temp[k++]=a[i++];
        }else {
        temp[k++]=a[j++];}
    }
    while(i<=mid)
    {
        temp[k++]=a[i++];
    }
    while(j<=last)
    {
        temp[k++]=a[j++];
    }
    for(int i=0;i<k;i++)
    {
        a[first+i]=temp[i];
    }
}
void    memgersort(int a[],int first,int last,int temp[])
{
        if(first>=last)
        {
            return ;
        }
        int mid=(first+last)/2;
        memgersort(a,first,mid,temp);
        memgersort(a,mid+1,last,temp);
        memger(a,first,mid,last,temp);
}
int main()
{
    while(cin>>n)
    {
        for(int i=0;i<n;i++)
        {
            cin>>a[i];
        }
        memgersort(a,0,n-1,temp);
        for(int i=0;i<n;i++)
        {
          cout<<a[i]<<" ";
        }
        cout<<endl;
    }
}