![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 /** 2 * 大根堆。从STL中获得。 3 */ 4 5 #include <iostream> 6 #include <ctime> 7 #include <cmath> 8 #include <cstdlib> 9 10 using namespace std; 11 12 void _push_heap(int *start, int holeIndex, int topIndex, int value) 13 { 14 int parent = (holeIndex - 1) / 2; 15 while (holeIndex > topIndex && *(start + parent) < value) 16 { 17 *(start + holeIndex) = *(start + parent); 18 holeIndex = parent; 19 parent = (holeIndex - 1) / 2; 20 } 21 *(start + holeIndex) = value; 22 } 23 24 void adjust_heap(int *start, int holeIndex, int length, int value) 25 { 26 int topIndex = holeIndex; 27 int secondChild = 2 * holeIndex + 2; 28 29 while (secondChild < length) 30 { 31 // 大根堆的调整 32 if (*(start + secondChild) < *(start + secondChild - 1)) 33 secondChild--; 34 *(start + holeIndex) = *(start + secondChild); 35 holeIndex = secondChild; 36 secondChild = 2 * holeIndex + 2; 37 } 38 39 if (secondChild == length) { 40 *(start + holeIndex) = *(start + secondChild - 1); 41 holeIndex = secondChild - 1; 42 } 43 44 _push_heap(start, holeIndex, topIndex, value); 45 } 46 47 48 void push_heap(int *start, int *end) 49 { 50 _push_heap(start, start - end - 1, 0, *(end - 1)); 51 } 52 53 int pop_heap(int *start, int *end) 54 { 55 int result = *start; 56 adjust_heap(start, 0, end - start, *(end - 1)); 57 58 return result; 59 } 60 61 void make_heap(int *start, int *end) 62 { 63 if (end - start < 2) return ; 64 int length = end - start; 65 int parent = (length - 2) / 2; 66 67 while (true) { 68 adjust_heap(start, parent, length, *(start + parent)); 69 if (parent == 0) return; 70 parent--; 71 } 72 } 73 74 void sort_heap(int *start, int *end) 75 { 76 while (end - start > 1) 77 cout << pop_heap(start, end--) << "\t" ; 78 } 79 80 int test(void) 81 { 82 enum {maxsize = 500}; 83 int a[maxsize], i; 84 srand((int)time(0)); 85 86 cout << "test array: " << endl; 87 for (i = 0; i < maxsize; i++) 88 { 89 a[i] = rand(); 90 cout << a[i] << "\t"; 91 } 92 int size = sizeof(a) / sizeof(int); 93 cout << endl << endl; 94 cout << "result: " << endl; 95 96 make_heap(a, a + size); 97 sort_heap(a, a + size); 98 99 return 0; 100 } 101 102 int main() 103 { 104 test(); 105 106 return 0; 107 }