// 交换两个整数的辅助函数voidswap(int* a, int* b) {
int t = *a;
*a = *b;
*b = t;
}
// 向上调整算法voidAdjustUp(type* a, int child) {
assert(a);
int parent = (child - 1) / 2;
while (child > 0) {
if (a[parent] < a[child]) { // 大根堆:父节点小于子节点则交换
swap(&a[parent], &a[child]);
child = parent;
parent = (child - 1) / 2;
} else {
break;
}
}
}
// 堆的插入入口voidHPPush(HP* h, type x) {
assert(h);
// 检查是否需要扩容if (h->capacity == h->size) {
int n = h->capacity == 0 ? 4 : 2 * h->capacity;
type* tmp = (type*)realloc(h->a, n * sizeof(type));
if (tmp == NULL) {
perror("realloc failed");
return;
}
h->a = tmp;
h->capacity = n;
}
// 插入数据
h->a[h->size++] = x;
// 向上调整
AdjustUp(h->a, h->size - 1);
}
4. 堆打印值
堆打印值实际上与顺序表的值的打印一样,只是结果是按照堆的值的顺序。
voidHPPrint(HP* h) {
assert(h);
int i;
for (i = 0; i < h->size; i++) {
printf("%d ", h->a[i]);
}
printf("\n");
}
测试代码
本代码分三个文件完成,便于模块化维护。
heap.h
#include<stdio.h>#include<assert.h>#include<stdlib.h>typedefint type;
typedefstructHeap {
type* a;
int size;
int capacity;
} HP;
voidHPInit(HP* h);
voidHPDestroy(HP* h);
voidHPPush(HP* h, type x);
voidAdjustUp(type* a, int child);
voidswap(int* a, int* b);
voidHPPrint(HP* h);
heap.c
#include"heap.h"voidHPInit(HP* h) {
assert(h);
h->a = NULL;
h->capacity = h->size = 0;
}
voidHPDestroy(HP* h) {
assert(h);
if (h->a) {
free(h->a);
}
h->capacity = h->size = 0;
}
voidswap(int* a, int* b) {
int t = *a;
*a = *b;
*b = t;
}
voidAdjustUp(type* a, int child) {
assert(a);
int parent = (child - 1) / 2;
while (child > 0) {
if (a[parent] < a[child]) {
swap(&a[parent], &a[child]);
child = parent;
parent = (child - 1) / 2;
} else {
break;
}
}
}
voidHPPush(HP* h, type x) {
assert(h);
if (h->capacity == h->size) {
int n = h->capacity == 0 ? 4 : 2 * h->capacity;
type* tmp = (type*)realloc(h->a, n * sizeof(type));
if (tmp == NULL) {
perror("realloc failed");
return;
}
h->a = tmp;
h->capacity = n;
}
h->a[h->size++] = x;
AdjustUp(h->a, h->size - 1);
}
voidHPPrint(HP* h) {
assert(h);
int i;
for (i = 0; i < h->size; i++) {
printf("%d ", h->a[i]);
}
printf("\n");
}