递归实现归并排序
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /************************************************************************* 2 > File Name: merge_sort.cpp 3 > Author: 4 > Description: 5 > Created Time: Sun 26 Jul 2015 10:15:24 AM HKT 6 ************************************************************************/ 7 8 #include<iostream> 9 using namespace std; 10 11 void merge(int a[],int tmp[],int lPos,int rPos,int rEnd) 12 { 13 int numElements=rEnd-lPos+1;// 计算元素个数 14 int lEnd=rPos-1; 15 int tmpPos=lPos; 16 while(lPos<=lEnd && rPos<=rEnd) 17 { 18 if(a[lPos]<=a[rPos]) 19 tmp[tmpPos++]=a[lPos++]; 20 else 21 tmp[tmpPos++]=a[rPos++]; 22 } 23 24 //到这里左端或右端可能还有剩余元素 25 while(lPos<=lEnd) 26 tmp[tmpPos++]=a[lPos++]; 27 while(rPos<=rEnd) 28 tmp[tmpPos++]=a[rPos++]; 29 30 for(int i=0;i<numElements;i++) 31 { 32 a[rEnd]=tmp[rEnd--]; 33 } 34 } 35 36 void msort(int a[],int tmp[],int low,int high) 37 { 38 if(low>=high) 39 return; 40 int middle=(low+high)/2; 41 msort(a,tmp,low,middle); 42 msort(a,tmp,middle+1,high); 43 merge(a,tmp,low,middle+1,high); 44 } 45 46 void merge_sort(int a[],int len) 47 { 48 int *tmp=new int[len]; 49 if(tmp !=NULL) 50 { 51 msort(a,tmp,0,len-1); 52 delete []tmp; 53 } 54 } 55 int main() 56 { 57 int a[]={1,4,7,6,3,8,2,5}; 58 merge_sort(a,8); 59 for(int i=0;i<8;i++) 60 { 61 cout<<a[i]<<" "; 62 } 63 cout<<endl; 64 65 return 0; 66 }