自定义Heap结构体,通过“向上调整算法”将元素插入到数组中,实现小堆/大堆的创建;然后,在实现删除堆顶元素的操作过程中,通过交换首尾元素并调用“向下调整算法”,保证堆结构的正确性。最后,在main函数中测试即可。
头文件:
#pragma once
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include <iostream>
using namespace std;
typedef int HPDataType;
typedef struct Heap
{
HPDataType* a; // 数组
int size; // 大小
int capacity; // 容量
}HP;
void HeapInit(HP* php); // 初始化
void HeapDestroy(HP* php); // 销毁
void HeapPush(HP* php, HPDataType x); // 插入
void AdjustUp(HPDataType* a, int child); // 向上调整
void HeapPop(HP* php); // 删除堆顶数据
void AdjustDown(HPDataType* a, int n, int parent); // 向下调整
HPDataType HeapTop(HP* php); // 获取堆顶数据
bool HeapEmpty(HP* php); // 判空
源文件:
#include "Heap.h"
void HeapInit(HP* php)
{
assert(php);
php->a = NULL;
php->size = 0;
php->capacity = 0;
}
void HeapDestroy(HP* php)
{
}
void AdjustUp(HPDataType* a, int child) // “向上调整算法”
{
int parent = (child - 1) / 2;
while (child > 0)
{
if (a[child] < a[parent]) // 以小堆为例,如果子节点比父节点小则交换(改成'>'即可改成大堆)
{
HPDataType tmp = a[child];
a[child] = a[parent];
a[parent] = tmp;
child = parent; // 继续往上走
parent = (child - 1) / 2;
}
else
{
break;
}
}
}
void AdjustDown(HPDataType* a, int n, int parent) // “向下调整算法”
{
int child = parent * 2 + 1;
while (child < n)
{
// 以小堆为例,选出左右孩子中小的那个
if (child+1 < n && a[child + 1] < a[child]) // 如果右孩子小
{
child++;
}
if (a[child] < a[parent]) // 如果孩子比父小,交换
{
HPDataType tmp = a[child];
a[child] = a[parent];
a[parent] = tmp;
parent = child; // 继续往下走
child = parent * 2 + 1;
}
else
{
break;
}
}
}
void HeapPush(HP* php, HPDataType x)
{
assert(php);
if (php->capacity == php->size)
{
int newCapacity = php->capacity == 0 ? 4 : php->capacity * 2; // 扩容
HPDataType* tmp = (HPDataType*)realloc(php->a, newCapacity * sizeof(HPDataType));
if (tmp == NULL)
{
perror("realloc error");
return;
}
php->a = tmp;
php->capacity = newCapacity;
}
php->a[php->size] = x; // 将插入的数据放在数组尾部
php->size++;
AdjustUp(php->a, php->size-1); // 新插入的数据只会影响它的祖先,所以要不断“向上调整”
}
void HeapPop(HP* php)
{
//要删除堆顶元素,方法:首尾数据交换,再删除,再调堆
//交换首尾、删除尾元素后,树的结构没有太大变化,此时非常适合对堆顶元素用“向下调整算法”
//“向下调整算法”前提要求其左右子树必须是堆,此时的堆顶元素正好符合要求
assert(php);
assert(!HeapEmpty(php));
HPDataType tmp = php->a[0];
php->a[0] = php->a[php->size - 1];
php->a[php->size - 1] = tmp;
php->size--;
AdjustDown(php->a, php->size, 0); // 对堆顶元素进行“向下调整”
}
HPDataType HeapTop(HP* php)
{
assert(php);
assert(!HeapEmpty(php));
return php->a[0];
}
bool HeapEmpty(HP* php)
{
assert(php);
if (php->size == 0) return true;
return false;
}
int main()
{
int a[] = { 7,4,5,6,3,8,2,1,9 };
HP hp;
HeapInit(&hp);
for (int i = 0; i < sizeof(a) / sizeof(HPDataType); ++i)
{
HeapPush(&hp, a[i]);
}
for (int i = 0; i < hp.size; ++i)
{
std::cout << hp.a[i] << "\t";
}
std::cout << std::endl;
return 0;
}