1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| #include <stdio.h> #include <string.h> #define N 8 void TreeSelectionSort(int *mData) { int MinValue = 0; int tree[N * 4]; // 树的大小 int max, maxIndex, treeSize; int i, n = N, baseSize = 1; while (baseSize < n) baseSize *= 2; treeSize = baseSize * 2 - 1; for (i = 0; i < n; i++) {//将要排的数字填到树上 tree[treeSize - i] = mData[i]; } for (; i < baseSize; i++) {//其余的地方都填上最小值 tree[treeSize - i] = MinValue; } // 构造一棵树,大的值向上构造 for (i = treeSize; i > 1; i -= 2) { tree[i / 2] = (tree[i] > tree[i - 1] ? tree[i] : tree[i - 1]); }
n -= 1; while (n != -1) { max = tree[1]; //树顶为最大值 mData[n--] = max; //从大到小倒着贴到原数组上 maxIndex = treeSize; //最大值下标 while (tree[maxIndex] != max) { maxIndex--; }//找最大值下标 tree[maxIndex] = MinValue; while (maxIndex > 1) { if (maxIndex % 2 == 0) { tree[maxIndex / 2] = (tree[maxIndex] > tree[maxIndex + 1] ? tree[maxIndex] : tree[maxIndex + 1]); } else { . tree[maxIndex / 2] = (tree[maxIndex] > tree[maxIndex - 1] ? tree[maxIndex] : tree[maxIndex - 1]); } maxIndex /= 2; } } } int main() { int a[N] = { 49,38,65,97,76,13,27,49 }; TreeSelectionSort(a); for (int i = 0; i < N; i++) { printf("%d ", a[i]); } return 0; }
|