这个没什么好说的,就是归并排序;
时间复杂度O(nlogn)
空间复杂度O(n)
#include<iostream>
using namespace std;
void merge(int A[],int low,int middle,int high)
{
int i,j,k;
int *B=new int [high-low+1];
i=low;
k=low;
j=middle+1;
while(i<=middle && j<=high)
{
if(A[i]<A[j])
B[k++]=A[i++];
else
B[k++]=A[j++];
}
while(i<=middle)
B[k++]=A[i++];
while(j<=high)
B[k++]=A[j++];
for(i=low;i<=high;i++)
A[i]=B[i];
}
void mergeSort(int A[],int low,int high)
{
int middle;
if(low<high)
{
middle=(low+high)/2;
mergeSort(A,low,middle);
mergeSort(A,middle+1,high);
merge(A,low,middle,high);
}
}
int main()
{
int A[]={1,3,5,7,2,4,6,8};
mergeSort(A,0,7);
for(int i=0;i<8;i++)
cout<<A[i]<<' ';
cout<<endl;
}