这是用分治法来对序列进行排序,将较长的一个序列分解为n个比较短的序列,然后分别处理这n个较小的段序列,最后合并。使用递归的来实现。
具体实现的代码如下:
1 void MergeSort(int *A, int p, int r) 2 { 3 if(p < r) 4 { 5 int q = ( p + r ) / 2; 6 MergeSort(A, p, q); 7 MergeSort(A, q + 1, r); 8 Merge(A, p, q, r); 9 } 10 } 11 void Merge(int *A, int p, int q, int r) 12 { 13 int n1 = q - p + 1; 14 int n2 = r - q ; 15 int *L1 = new int[ (n1 + 1) * sizeof(int)]; 16 int *R1 = new int[ (n2 + 1) * sizeof(int)]; 17 int iLoop; 18 int jLoop; 19 20 for(iLoop = 0; iLoop != n1; ++iLoop) 21 { 22 L1[iLoop] = A[p + iLoop]; 23 } 24 for( jLoop = 0; jLoop != n2; ++jLoop) 25 { 26 R1[jLoop] = A[q + jLoop + 1]; 27 } 28 L1[n1 ] = INT_MAX; 29 R1[n2 ] = INT_MAX; 30 31 jLoop = 0; 32 iLoop = 0; 33 for (int kLoop = p; kLoop != r + 1; ++kLoop) 34 { 35 if(L1[iLoop] <= R1[jLoop]) 36 { 37 A[kLoop] = L1[iLoop++]; 38 } 39 else 40 { 41 A[kLoop] = R1[jLoop++]; 42 } 43 } 44 delete L1;
delete R1; 45 }
算法还需要深入思考,to be continued