heap.h
#pragma once
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
typedef int HeapDataType;
typedef struct Heap
{
HeapDataType* _a;
int _size;
int _capacity;
}Heap;
void Swap(HeapDataType* p1, HeapDataType* p2);
void AdjustDown(HeapDataType* a, int n,int root);
void HeapInit(Heap* php, HeapDataType* a, int n);
void HeapDestory(Heap* php);
void HeapPush(Heap* php,HeapDataType x);
void HeapPop(Heap* php);
HeapDataType HeapTop(Heap* php);
heap.c
#include"Heap.h"
void HeapInit(Heap* php, HeapDataType* a, int n)
{
php->_a = (HeapDataType*)malloc(sizeof(HeapDataType) * n);
memcpy(php->_a, a, sizeof(HeapDataType)*n);
php->_size = n;
php->_capacity = n;
//构建堆
for (int i = (n - 1 - 1) / 2; i >= 0; --i)
{
AdjustDown(php->_a, php->_size, i);
}
}
void Swap(HeapDataType* p1, HeapDataType* p2)
{
HeapDataType tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
void AdjustUp(HeapDataType* a, int n, int child)
{
int parent = (child - 1) / 2;
while (child)
{
if (a[child] < a[parent])
{
Swap(&a[child],& a[parent]);
child = parent;
parent = (child - 1) / 2;
}
else
{
break;
}
}
}
void AdjustDown(HeapDataType* a, int n,int root)
{
int parent = root;
int child = parent * 2 + 1;
while (child<n)
{
if (child+1<n&&a[child + 1] < a[child])
{
++child;
}
if (a[child] < a[parent])
{
Swap(&a[child], &a[parent]);
}
else
{
break;
}
}
}
void HeapDestory(Heap* php)
{
assert(php);
free(php->_a);
php->_a = NULL;
php->_capacity = php->_size = 0;
}
void HeapPush(Heap* php, HeapDataType x)
{
assert(php);
if (php->_size == php->_capacity)
{
php->_capacity *= 2;
HeapDataType* tmp =(HeapDataType*) realloc(php->_a,sizeof(HeapDataType) * php->_capacity);
php->_a = tmp;
}
php->_a[php->_size++] = x;
AdjustUp(php->_a, php->_size, php->_size - 1);
}
void HeapPop(Heap* php)
{
assert(php);
assert(php->_size > 0);
Swap(&php->_a[0], &php->_a[php->_size - 1]);
php->_size--;
AdjustDown(php->_a, php->_size, 0);
}
HeapDataType HeapTop(Heap* php)
{
assert(php);
assert(php->_size);
return php->_a[0];
}