合并排序算法的时间复杂度为O(nlogn), 是渐近意义下的最优算法。合并算法也是分治算法的应用例子。
合并算法的基本思想:将待排序元素分成大小大致相等的2个子集合,分别对这2个子集合进行排序,最后将排好序的子集合合并
成为所要求的排好序的集合。
算法实现:
1 template<typename T> 2 void merge_array(T a[], int beg, int end) 3 { 4 int center = (beg + end) / 2; 5 for (int i=beg, j=center+1; i<=end && j<=end;) { 6 if (a[i] > a[j]) { 7 T tm = a[j]; 8 for(int k=j; k!=i; --k) 9 a[k] = a[k-1]; 10 a[i] = tm; 11 j++; 12 i++; 13 } 14 else 15 i++; 16 } 17 } 18 19 template<typename T> 20 void m_sort(T a[], int left, int right) 21 { 22 if (left < right) { 23 int center = (left + right) / 2; 24 m_sort(a,left,center); 25 m_sort(a,center+1,right); 26 merge_array(a,left,right); 27 } 28 } 29 30 template<typename T> 31 void mergesort(T a[], int n) 32 { 33 m_sort(a,0,n-1); 34 }