堆的实现:
#include <iostream >
using namespace std;
#include <assert.h>
typedef struct Heap
{
int* array;
int size;
int capacity;
}HP;
void HeapInit(HP* hp)
{
hp->array = nullptr;
hp->capacity = hp->size = 0;
}
void HeapDestroy(HP* hp)
{
assert(hp);
free(hp->array);
hp->array = nullptr;
hp->capacity = hp->size = 0;
}
void swap(int* hp1, int* hp2)
{
int tmp = *hp1;
*hp1 = *hp2;
*hp2 = tmp;
}
//小堆
void adjustUp(int* array, int child)
{
int parent = (child - 1) / 2;
while (child>0)
{
if (array[child] < array[parent])
{
swap(&(array[child]), &(array[parent]));
child = parent;
parent = (child - 1) / 2;
}
else
{
break;
}
}
}
void HeapPush(HP* hp, int x)
{
assert(hp);
if (hp->size == hp->capacity)
{
//扩容
int newCapacity = hp->capacity == 0 ? 4 : hp->capacity * 2;
int* newA =(int*) realloc(hp->array, sizeof(int) * newCapacity);
if (newA==nullptr)
{
printf("realloc fail");
}
hp->capacity = newCapacity;
hp->array = newA;
}
hp->array[hp->size] = x;
hp->size++;
adjustUp(hp->array,hp->size-1);
}
int HeapTop(HP* hp)
{
assert(hp);
assert(hp->size > 0);
return hp->array[0];
}
bool HeapEmpty(HP* hp)
{
assert(hp);
return hp->size == 0;
}
int HeapSize(HP* hp)
{
assert(hp);
return hp->size;
}
void adjustDown(int* array, int parent, int size)
{
//默认最小孩子为左孩子
int child = parent * 2 + 1;
//判断
while (child < size)
{
//确保child为最小孩子
if (child + 1 < size && array[child + 1] < array[child])
{
child = child + 1;
}
if (array[child] < array[parent])
{
swap(&(array[child]), &array[parent]);
parent = child;
child = parent * 2 + 1;
}
else
{
break;
}
}
}
void HeapPop(HP* hp)
{
assert(hp);
assert(hp->size > 0);
swap(&(hp->array[0]), &(hp->array[hp->size - 1]));
hp->size--;
adjustDown(hp->array,0,hp->size);
}
题目需要的代码:
int main()
{
HP hp;
HeapInit(&hp);
int a[] = { 27,15,19,18,28,34,65,49,25,37 };
for (int i = 0; i < sizeof(a) / sizeof(int); i++)
{
HeapPush(&hp, a[i]);
}
while (!HeapEmpty(&hp))
{
cout << HeapTop(&hp) << " " ;
HeapPop(&hp);
}
HeapDestroy(&hp);
}