这里先给出总代码,后面为详细图解
总代码:
heap.h:
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
#include<stdbool.h>
typedef int HPDataType;
typedef struct Heap {//创建堆
HPDataType* a;
size_t capacity;
size_t size;
}HP;
void HeapInit(HP* php);//初始化堆
void HeapDestroy(HP* php);//销毁堆
void HeapPush(HP* php,HPDataType x);//插入
void HeapPop(HP* php);//删除
void HeapPrintf(HP* php);//打印
void adjustup(HPDataType* a, size_t child);//向上调整
void adjustdown(HPDataType* a, size_t size, size_t root);//向下调整
void Swap(HPDataType* pa, HPDataType* pb);//交换
bool HeapEmpty(HP* php);
size_t HeapSize(HP* php);
HPDataType HeapTop(HP* php);
heap.c:
#define _CRT_SECURE_NO_WARNINGS 1
#include"heap.h"
void HeapInit(HP* php)//初始化堆
{
assert(php);
php->a = NULL;
php->capacity = php->size = 0;
}
void HeapDestroy(HP* php)//销毁堆
{
assert(php);
free(php->a);
php->a = NULL;
php->size = php->capacity = 0;
}
void adjustdown(HPDataType* a,size_t size,size_t root)//向下调整
{
size_t parent = root;
size_t child = parent * 2 + 1;
while (child < size)
{
if (child+1<size&&a[child + 1] < a[child])
{
child++;
}
if (a[child] < a[parent])
{
Swap(&a[child], &a[parent]);
parent = child;
child = parent * 2 + 1;
}
else
{
break;
}
}
}
void adjustup(HPDataType* a, size_t child)//向上调整
{
size_t parent = (child - 1) / 2;
while (child>0)
{
if (a[child] < a[parent])
{
Swap(&a[child], &a[parent]);
child = parent;
parent = (child - 1) / 2;
}
else
{
break;
}
}
}
void Swap(HPDataType* pa, HPDataType* pb)//交换
{
HPDataType tmp = *pa;
*pa = *pb;
*pb = tmp;
}
void HeapPush(HP* php, HPDataType x)//插入
{
assert(php);
if (php->capacity == php->size)
{
size_t newcapacity = php->capacity == 0 ? 4 : php->capacity * 2;
HPDataType* tmp = realloc(php->a, sizeof(HPDataType) * newcapacity);
if (tmp == NULL)
{
printf("realloc fail");
exit(-1);
}
php->a = tmp;
php->capacity = newcapacity;
}
php->a[php->size] = x;
php->size++;
adjustup(php->a, php->size - 1);
}
void HeapPrintf(HP* php)//打印
{
assert(php);
for (int i = 0; i < php->size; i++)
{
printf("%d", php->a[i]);
}
printf("\n");
}
void HeapPop(HP* php)//删除
{
assert(php);
Swap(&php->a[0], &php->a[php->size - 1]);
php->size--;
adjustdown(php->a, php->size, 0);
}
bool HeapEmpty(HP* php)
{
assert(php);
return php->size == 0;
}
size_t HeapSize(HP* php)
{
assert(php);
return php->size;
}
HPDataType HeapTop(HP* php)
{
assert(php);
assert(php->size > 0);
return php->a[0];
}
test.c:
#define _CRT_SECURE_NO_WARNINGS 1
#include"heap.h"
void test()
{
HP hp;
HeapInit(&hp);
HeapPush(&hp, 1);
HeapPush(&hp, 5);
HeapPush(&hp, 3);
HeapPush(&hp, 7);
HeapPush(&hp, 9);
HeapPush(&hp, 4);
HeapPush(&hp, 6);
HeapPush(&hp, 8);
HeapPrintf(&hp);
HeapPop(&hp);
HeapPrintf(&hp);
HeapDestroy(&hp);
}
int main()
{
test();
return 0;
}
图解:
我们模拟一次插入的过程,为了方便展示,我这里使用二叉树的形式,注意parent和child的变化
向上调整:
?向下调整:
?
|