//Heap.h
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>
typedef int HeapDatatype;
struct Heap
{
HeapDatatype* arr;
int size;
int capacity;
};
typedef struct Heap HP;
void HPInit(HP* php);
void HPDestroy(HP* php);
void HPPush(HP* php, HeapDatatype x);
HeapDatatype HPTop(HP* php);
void HPPop(HP* php);
HeapDatatype HPTop(HP* php);
bool HPEmpty(HP* php);
//Heap.c
#define _CRT_SECURE_NO_WARNINGS 1
#include"Heap.h"
void HPInit(HP* php)
{
assert(php);
php->arr = NULL;
php->size = 0;
php->capacity = 0;
}
void HPDestroy(HP* php)
{
assert(php);
free(php->arr);
php->arr = NULL;
php->size = 0;
php->capacity = 0;
}
void Swap(HeapDatatype* x, HeapDatatype* y)
{
HeapDatatype temp;
temp= *x;
*x = *y;
*y = temp;
}
void AdjustUp(HeapDatatype* arr, int child)
{
int parent = (child - 1) / 2;
while (child>0)
{
if (arr[child] > arr[parent])
{
Swap(&arr[parent], &arr[child]);
child = parent;
parent = (parent - 1) / 2;
}
else
{
break;
}
}
}
void HPPush(HP* php, HeapDatatype x)
{
assert(php);
size_t newcapacity;
if (php->size == php->capacity)
{
if (php->capacity == 0)
{
newcapacity = 4;
}
else
{
newcapacity = php->capacity * 2;
}
HeapDatatype* temp = realloc(php->arr, sizeof(HeapDatatype) * newcapacity);
if (temp == NULL)
{
perror("realloc fail!");
exit(1);
}
php->arr = temp;
php->capacity = newcapacity;
}
php->arr[php->size] = x;
php->size++;
AdjustUp(php->arr, php->size-1);
}
HeapDatatype HPTop(HP* php)
{
assert(php);
return php->arr[0];
}
AdjustDown(HeapDatatype* arr, int size, int parent)
{
int child = parent * 2 + 1;
while (child < size)
{
if (child+1<size && arr[child + 1] > arr[child])
{
child++;
}
if (arr[child] > arr[parent])
{
Swap(&arr[child], &arr[parent]);
parent = child;
child = child * 2 + 1;
}
else
{
break;
}
}
}
void HPPop(HP* php)
{
assert(php);
assert(php->size>0);
Swap(&php->arr[0], &php->arr[php->size - 1]);
php->size--;
AdjustDown(php->arr, php->size, 0);
}
bool HPEmpty(HP* php)
{
assert(php);
return php->size == 0;
}
//test.c
#define _CRT_SECURE_NO_WARNINGS 1
#include"Heap.h"
int main()
{
int arr[] = { 50,100,70,65,60,32 };
HP hp;
HPInit(&hp);
for (int i = 0; i < sizeof(arr) / sizeof(int); i++)
{
HPPush(&hp, arr[i]);
}
/*printf("%d\n", HPTop(&hp));
HPPop(&hp);
printf("%d\n", HPTop(&hp));*/
while (!HPEmpty(&hp))
{
printf("%d\n", HPTop(&hp));
HPPop(&hp);
}
HPDestroy(&hp);
return 0;
}