1 #include <iostream> 2 #include <stdlib.h> 3 4 using namespace std; 5 #define N 100 6 7 //合并序列中的s:m-1和m:e两个子序列 8 void merge(int array[], int s, int m, int e) { 9 int ta[N], i, j, k = 0; 10 i = s; 11 j = m; 12 while (i < m && j <= e) { 13 if (array[i] < array[j]) { 14 ta[k++] = array[i++]; 15 } else { 16 ta[k++] = array[j++]; 17 } 18 } 19 while (i < m) { 20 ta[k++] = array[i++]; 21 } 22 while (j <= e) { 23 ta[k++] = array[j++]; 24 } 25 i = s; 26 k = 0; 27 while (i <= e) { 28 array[i++] = ta[k++]; 29 } 30 } 31 32 //自底向上归并 33 void buttomUpSort(int array[], int length) { 34 int i = 1, s, m, e, t; 35 while ((length / i) >= 1) { //依次从2, 4, 8......至序列被分成两部分向上归并 36 s = 0; 37 while (1) { 38 m = s + i; 39 if (m >= length)//若此段序列孤立(及原序列被划分成奇数个部分,最后一部分不做合并,进入到下一次合并) 40 break; 41 else { 42 e = ((t = m + i - 1) < length)?t:length - 1;//最后一段序列的截止位为length-1 43 merge(array, s, m, e); 44 } 45 s += i*2; 46 } 47 i *= 2; 48 } 49 } 50 51 int main(int args, char **argv) { 52 int array[N]; 53 for (int i = 0; i < N; ++i) { 54 array[i] = rand() % 100; 55 } 56 for (int i = 0; i < N; i++) { 57 cout << '\t' << array[i]; 58 } 59 cout << endl; 60 buttomUpSort(array, N); 61 for (int i = 0; i < N; i++) { 62 cout << '\t' << array[i]; 63 } 64 return 0; 65 }