#include<stdio.h>
void swap(int arr[], int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
void heapify(int tree[], int n, int i) {
if (i >= n) {
return;
}
int c1 = 2 * i + 1;
int c2 = 2 * i + 2;
int max = i;
if (c1 < n && tree[c1] > tree[max]) {
max = c1;
}
if (c2 < n && tree[c2] > tree[max]) {
max = c2;
}
if (max != i) {
swap(tree, max, i);
heapify(tree, n, max);
}
}
void build_heap(int tree[], int n) {
// 从倒数第二层开始进行heapify计算,为了的得到一个完整的堆
int last_node = n - 1;
int parent = (last_node - 1) / 2;
int i;
for (i = parent; i >= 0; i--) {
heapify(tree, n, i);
}
}
void heap_sort(int tree[], int n) {
build_heap(tree, n);
int i;
// i开始的时候等于最后一个节点
for (i = n - 1; i >= 0; i--) {
// 最后一个节点和最上面的节点进行一下交换
swap(tree, i, 0);
// 砍断,然后再进行一次heapify计算
heapify(tree, i, 0);
}
}
int main() {
int tree[] = {2, 5, 3, 1, 10, 4};
// int n = sizeof(tree) / sizeof(tree[0]);
int n = 6;
// printf("n=%d\n", n);
heap_sort(tree, n);
for (int i = 0; i < n; i++) {
printf("%d,", tree[i]);
}
printf("\n");
return 0;
}
08-20
9736
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
01-01
12-10
754
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-08
1万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交