1 /*实现堆*/
2 #include<iostream>
3 #include<algorithm>
4 void down(int* A, int node, int end);
5 void HEAP(int* A, int end);
6 using namespace std;
7 void show(int t){cout << t << " ";}
8 void main(){
9
10 int A[] = {4,3,6,5,7,1};
11 int end = 5;
12 HEAP(A, end);
13 for_each(A, A+6, show);
14 cout << endl;
15
16 system("pause");
17 }
18
19 /*向下调整*/
20 void down(int* A, int node, int end){
21 int c, l;
22 c = node;
23 l = 2*c+1;
24 for(; l < end; c = l,l = 2*l+1)
25 {
26 int temp = A[c];
27 if(A[l] < A[l+1] )
28 ++l;
29 if(A[c] <= A[l])
30 {
31 A[c] = A[l];
32 A[l] = temp;
33 }
34 }
35 }
36
37 /*建堆*/
38 void HEAP(int* A, int end)
39 {
40 int node = (end-1)/2;
41 for(int i = node; i >=0; --i)
42 {
43 cout << node << "---";
44 for_each(A, A+6, show);
45 cout << endl;
46 down(A, i, end);
47 }
48 }