堆的定义
typedef int HPDataType;
typedef int(*pCompar)(HPDataType left, HPDataType right);
typedef struct Heap
{
HPDataType* _hp;
int _Capecity;
int _size;
pCompar _compar;
}Heap, *pHeap;
辅助函数
小于比较
int Less(HPDataType left, HPDataType right)
{
return left < right;
}
大于比较
int Greater(HPDataType left, HPDataType right)
{
return left > right;
}
交换函数
void Swap(HPDataType* Left, HPDataType* Right)
{
HPDataType tmp = 0;
tmp = *Left;
*Left = *Right;
*Right = tmp;
}
向下调整法
void AdjustDown(pHeap heap, int parent)
{
assert(heap);
int child;
child = (parent << 1) + 1;
while (child <= heap->_size - 1)
{
if (child + 1 < heap->_size)
{
if (heap->_compar((heap->_hp[child + 1]), (heap->_hp[child])))
child = child + 1;
}
if (heap->_compar((heap->_hp[child]), (heap->_hp[parent])))
{
Swap(&(heap->_hp[parent]), &(heap->_hp[child]));
parent = child;
child = (parent << 1) + 1;
}
else
return;
}
}
向上调整法
void AdjustUp(pHeap heap, int child)
{
assert(heap);
int parent = (child - 1) >> 1;
while(child > 0)
{
if (heap->_compar((heap->_hp[child]), (heap->_hp[parent])))
{
Swap(&(heap->_hp[parent]), &(heap->_hp[child]));
child = parent;
parent = (child - 1) >> 1;
}
else
return;
}
}
初始化
void Initheap(pHeap heap, HPDataType* arr, int size, pCompar compar)
{
assert(heap);
heap->_hp = (HPDataType*)malloc(size * sizeof(HPDataType));
if (NULL == heap->_hp)
{
assert(0);
}
memcpy(heap->_hp, arr, size * sizeof(HPDataType));
heap->_Capecity = size * sizeof(HPDataType);
heap->_size = size;
heap->_compar = compar;
}
创建堆
void Createheap(pHeap heap)
{
assert(heap);
int root = (heap->_size - 2) >> 1;
for (; root >= 0; root--)
AdjustDown(heap, root);
}
堆插入元素
void Insertheap(pHeap heap, HPDataType d)
{
assert(heap);
if (heap->_Capecity < (int)((heap->_size + 1) * sizeof(HPDataType)))
{
HPDataType* hp = (HPDataType*)malloc(heap->_size * 2 * sizeof(HPDataType));
if (NULL == heap->_hp)
{
assert(0);
}
memcpy(hp, heap->_hp, heap->_size * 2 * sizeof(HPDataType));
heap->_hp = hp;
heap->_Capecity = heap->_size * 2 * sizeof(HPDataType);
heap->_size = heap->_size + 1;
}
heap->_hp[heap->_size - 1] = d;
int child = heap->_size - 1;
AdjustUp(heap, child);
}
删除堆顶元素
void Romoveheap(pHeap heap)
{
assert(heap);
if (heap->_size == 0)
{
return;
}
Swap(&(heap->_hp[heap->_size - 1]), &(heap->_hp[0]));
heap->_size--;
AdjustDown(heap, 0);
}
堆元素个数
int Sizeheap(pHeap heap)
{
assert(heap);
return heap->_size;
}
堆是否为空
int Emptyheap(pHeap heap)
{
assert(heap);
return heap->_size == 0;
}
堆顶元素
int Topheap(pHeap heap)
{
assert(heap);
return heap->_hp[0];
}
销毁堆
void Restoyheap(pHeap heap)
{
assert(heap);
free(heap->_hp);
heap->_hp = NULL;
heap->_Capecity = 0;
heap->_size = 0;
}