分治法——3.3合并排序_趣学算法学习笔记

 

分治法——3.3合并排序_算法_02

分治法——3.3合并排序_算法_03

 

#include<iostream>
#include<cstdlib>
#incclude<cstdio>
using namespace std;
void Merge(int A[],int low,int mid,int high)
{
    int *B=new int[high-low+1];//申请一个辅助数组
    int i=low,j=mid+1,k=0;
    while(i<=mid&&j<=high)
    {
        if(A[i]<=A[j])
            B[k++]=A[i++];
        else
           B[k++]=A[j++];
    }
    while(i<=mid)
        B[k++]=A[i++];
    while(j<=high)
        B[k++]=A[j++];
    for(int i=low,k=0;i<=high;i++)
        A[i++]=B[k++];
}
void MergeSort(int A[],int low,int high)
{
    if(kow<high)
    {
        int mid=(low+high)/2;
        MergeSort(A,low,mid);
        MergeSort(A,mid+1,high);
        Merge(A,low,mid,high);
    }
}