递归:
1 void merge_array(int a[],int low,int mid,int end){ 2 int* temp = new int[end-low+1]; 3 int index_pre = low; 4 int index_post = mid+1; 5 int i=0; 6 while(index_pre<=mid&&index_post<=end){ 7 if(a[index_pre]<a[index_post]) 8 temp[i++] = a[index_pre++]; 9 else 10 temp[i++] = a[index_post++]; 11 } 12 if(index_pre<=mid)while(index_pre<=mid) 13 temp[i++] = a[index_pre++]; 14 if(index_post<=end)while(index_post<=end) 15 temp[i++] = a[index_post++]; 16 for(i=0;i<end-low+1;i++) 17 a[low+i] = temp[i]; 18 delete[] temp; 19 } 20 21 void merge_sort(int a[],int low, int high){ 22 if(low<high){ 23 int mid = (low+high)/2; 24 merge_sort(a,low,mid); 25 merge_sort(a,mid+1,high); 26 merge_array(a,low,mid,high); 27 } 28 }
非递归:
即以1,2,4,8...为间隔对数组进行归并,需要用到额外的空间。空间复杂度是O(n),时间复杂度为O(nlogn)。
1 void mergeArray2(int a[],int b[], int low,int mid,int high){ 2 int i=low,j=mid+1,k=i; 3 while(i<=mid&&j<=high){ 4 if(b[i]<b[j]){ 5 a[k++]=b[i++]; 6 }else{ 7 a[k++]=b[j++]; 8 } 9 } 10 while(j<=high) 11 a[k++]=b[j++]; 12 while(i<=mid) 13 a[k++]=b[i++]; 14 } 15 void mergepass(int a[],int b[],int s,const int length){ 16 int i=0; 17 while(i<=length-2*s){ 18 mergeArray2(a,b,i,i+s-1,i+2*s-1); 19 i = i+2*s; 20 } 21 if(i+s<length)mergeArray2(a,b,i,i+s-1,length-1); 22 else for(int j=i;j<length;j++)a[j]=b[j]; 23 } 24 void mergeSort(int temp[],const int length){ 25 int i=0; 26 int s=1; 27 int* temp1= new int[length]; 28 while(s<length){ 29 mergepass(temp1,temp,s,length); 30 s*=2; 31 mergepass(temp,temp1,s,length); 32 s*=2; 33 } 34 delete[] temp1; 35 }