条件:
1、完全二叉树(性质)
2、父节点大于子节点
比如
构建一个堆
子节点中最大值于父节点交换
从倒数第二次开始heapify
完全二叉树的性质
多个节点heapify
5 > Created Time: 2019年09月16日 星期一 23时23分40秒
6 ************************************************************************/
7
8 #include<stdio.h>
9 void swap(int arr[], int a, int b){
10 int temp =arr[a];
11 arr[a] = arr[b];
12 arr[b] = temp;
13 }
14
15 void heapify(int tree[], int n, int i){//堆化:满足堆的条件,
对第i节点堆化
16 if(i >= n){
17 return ;
18 }
19 int c1 = 2 * i + 1;//子节点,完全二叉树的性质
20 int c2 = 2 * i + 2;
21 int max = i;
22 if(c1 <n && tree[c1] > tree[max])
23 {
24 max = c1;
25 }
26 if(c2 < n && tree[c2] > tree[max])
27 {
28 max = c2;
29 }
30 if(max != i)
31 {
32 swap(tree,max,i);
33 heapify(tree,n,max);
34 }
35 }
36
37 void build_heap(int tree[], int n){//多个节点堆化
38 int last_node = n - 1;
39 int parent = (last_node - 1) / 2;
40 int i;
41 for(i = parent; i >= 0; i--){
42 heapify(tree,n,i);
43 }
44 }
45
46 void heap_sort(int tree[], int n){//堆的排序
47 build_heap(tree,n);
48 int i;
49 for(i = n - 1; i >= 0; i--){
50 swap(tree,i,0);//把第一个节点于最后一个节点交换
51 heapify(tree,i,0);
52 }
53 }
54
55 int main()
56 {
57 int arr[]={
58 2,5,3,1,10,4
59 };
60 int n = 6;
61 // heapify(arr,n,0);
62 // build_heap(arr,n);
63 heap_sort(arr,n);
64 int i;
65 for(i = 0; i < n; i++)
66 {
67 printf("%d\n",arr[i]);
68 }
69 return 0;
70 }