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
| #include <iostream> using namespace std; void max_heap(int arry[], int begin, int end) { int root = begin; int left = root * 2 + 1; int right = root * 2 + 2; while (left <= end) { if (arry[left] < arry[right] && right <= end) left++; if (arry[left] < arry[root]) return; else { swap(arry[left], arry[root]); root = left; left = root * 2 + 1; right = root * 2 + 2; } } } void sort(int arry[], int end) { for (int i = end / 2; i >= 0; i--) max_heap(arry, i, end); for (int i = end; i > 0; i--) { swap(arry[0], arry[i]); max_heap(arry, 0, i-1 ); } } int main() { int arry[11] = { 5, 8, 1, 4, 2, 3, 9, 10, 7, 14, 16 }; sort(arry, 10); return 0; }
|