今天复习算法, 自然归并算法令我挺感兴趣,结果网上找到的基本都不怎么准确,下面通过自己的一些修改,贴出一份正确的代码!
自然归并中,有一些已经自然排好序的序列,我们称其为有序子序列!
1 void NaturalMergeSort(T aSrc[], int n)
2 {
3 T *pTmp = new T[n];
4 int aiBreakPoint[n]; //包含各有序子序列断点
5 int iBpCnt = 0; //断点数量
6 aiBreakPoint[iBpCnt++] = 0; //aiBreakPoint[0]永远指向第一个元素
7 for (int i=0; i<n-1 ; i++ ) //扫描断点
8 {
9 if(aSrc[i] > aSrc[i+1])
10 aiBreakPoint[iBpCnt++] = i + 1;
11 }
12 aiBreakPoint[iBpCnt++] = n-1;
13
14 while(iBpCnt > 2)//直到断点数为2
15 {
16 int i=0, iNewBpCnt = 1;
17 for (i = 0; i < iBpCnt - 2; i += 2)
18 {
19 Merge(aSrc, pTmp, aiBreakPoint[i], aiBreakPoint[i+1], aiBreakPoint[i+2]);//相邻两个合并
20
21 for (int j = aiBreakPoint[i]; j <= aiBreakPoint[i+2]; j++ ) //复制结果
22 aSrc[j] = pTmp[j];
23
24 aiBreakPoint[iNewBpCnt++] = aiBreakPoint[i+2];
25 }
26
27 if(i == iBpCnt - 2)
28 aiBreakPoint[iNewBpCnt++] = aiBreakPoint[iBpCnt-1]; //处理最后的孤立点
29
30 iBpCnt = iNewBpCnt;
31 }
delete[] pTmp;
32 }
33
34 void Merge(T c[], T d[], int l, int m, int r)
35 {
36 // Merge c[l:m]] and c[m:r] to d[l:r].
37 int i = l, // cursor for first segment
38 j = m+1, // cursor for second
39 k = l; // cursor for result
40
41 // merge until i or j exits its segment
42 while ((i <= m) && (j <= r))
43 if (c[i] <= c[j]) d[k++] = c[i++];
44 else d[k++] = c[j++];
45
46 // take care of left overs
47 if (i > m) for (int q = j; q <= r; q++)
48 d[k++] = c[q];
49 else for (int q = i; q <= m; q++)
50 d[k++] = c[q];
51 }
by wink.