分治算法-归并排序
1 #include<iostream> 2 using namespace std; 3 4 void Merger_Sort(int a[],int low,int high) 5 { 6 int temp[20]; 7 if(low==high) 8 return ; 9 else 10 { 11 int mid=(low+high)/2; 12 int i=low,j=mid+1,l=low; 13 Merger_Sort(a,low,mid); 14 Merger_Sort(a,mid+1,high); 15 while(i<=mid && j<=high) 16 { 17 if(a[i]<a[j]) 18 temp[l++]=a[i++]; 19 else 20 temp[l++]=a[j++]; 21 } 22 while(i<=mid) 23 temp[l++]=a[i++]; 24 while(j<=high) 25 temp[l++]=a[j++]; 26 for(i=low;i<=high;i++) 27 a[i]=temp[i]; 28 } 29 } 30 void print(int a[],int n) 31 { 32 for(int i=0;i<n;i++) 33 cout<<a[i]<<" "; 34 cout<<endl; 35 } 36 int main() 37 { 38 int a[10]={3,5,7,1,2,9,8,11,10,4}; 39 print(a,10); 40 Merger_Sort(a,0,9); 41 print(a,10); 42 return 0; 43 }