归并排序的递归实现

#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;

void msort (int low,int high,int *a,int *t);
void mergee(int low,int high,int mid,int *a,int *t);

int main()
{
        int n;
        int  a[1000],t[1000];
        cin>>n;
        for(int i=0;i<n;i++)
                cin>>a[i];
      msort(0,n-1,a,t);
        for(int i=0;i<n;i++)
                cout<<a[i]<<endl;


    return 0;
}
void msort(int low,int high,int *a,int *t)
{
int mid=(low+high)/2;
if(low<high)
{

        msort(low,mid,a,t);
        msort(mid+1,high,a,t);
}
mergee(low,high,mid,a,t);
}

void mergee(int low,int high,int mid,int *a,int *t)
{
        int i=low,k=low;
        int j=mid+1;
        while(i<=mid&&j<=high)
        {
                if(a[i]<=a[j])
                {
                        t[k++]=a[i++];
                }
                else
                {
                        t[k++]=a[j++];
                }
        }
        while(i<=mid)
        {
        t[k++]=a[i++];
        }
        while(j<=high)
        {
        t[k++]=a[j++];
        }
        for(int x=low;x<=high;x++)
        {
                a[x]=t[x];
        }

}

猜你喜欢

转载自blog.csdn.net/qq_34552393/article/details/79245730