头文件
#include"stdio.h"
#include"malloc.h"
#include "assert.h"
typedef int DataType;
typedef struct Heap
{
DataType* _hp;
int _capacity;
int _size;
}Heap;
void CreateHeap(Heap* pHp, DataType array[], int size);
void InitHeap(Heap* pHp);
void Insert(Heap* pHp, DataType data);
void Remove(Heap* pHp);
int EmptyHeap(Heap* pHp);
int SizeHeap(Heap* pHp);
void AdjustDown(Heap* pHp, int Root);
void AdjustUp(Heap* pHp, int child);
DataType Top(Heap* pHp);
void CheckCapacity(Heap* pHp);
void HeapSort(Heap* pHp,int size);
void Swap(int left, int right);
函数实现部分
#include"Heap.h"
void CreateHeap(Heap* pHp, DataType arr[], int size)
{
pHp->_hp = (DataType*)malloc(sizeof(DataType)*(size + 3));
if (NULL == pHp->_hp)
{
return;
}
pHp->_capacity = size + 3;
pHp->_size = size;
for (int i = 0; i < size; i++)
{
pHp->_hp[i] = arr[i];
}
int root = (size - 2) / 2;
for (; root >= 0; root--)
{
AdjustDown(pHp, root);
}
}
void InitHeap(Heap* pHp)
{
assert(pHp);
pHp->_hp = NULL;
pHp->_capacity = 0;
pHp->_size = 0;
}
void Insert(Heap* pHp, DataType data)
{
assert(pHp);
pHp->_hp[pHp->_size++] = data;
if (pHp->_size>1)
AdjustUp(pHp, pHp->_size - 1);
}
void Remove(Heap* pHp)
{
assert(pHp);
if (EmptyHeap(pHp))
{
return;
}
Swap(pHp->_hp[0], pHp->_hp[pHp->_size - 1]);
pHp->_size--;
AdjustDown(pHp, pHp->_hp[0]);
}
int EmptyHeap(Heap* pHp)
{
assert(pHp);
if (NULL == pHp->_hp)
{
return 1;
}
return 0;
}
int SizeHeap(Heap* pHp)
{
return pHp->_size;
}
void AdjustDown(Heap* pHp, int Root)
{
int parent = 0;
int child = 2 * parent + 1;
while (child < pHp->_size)
{
if (pHp->_hp[child] >pHp->_hp[child + 1])
{
child = child + 1;
}
if (pHp->_hp[parent] > pHp->_hp[child])
{
Swap(pHp->_hp[parent], pHp->_hp[child]);
parent = child;
child = parent * 2 + 1;
}
}
}
void AdjustUp(Heap* pHp, int child)
{
int parent = (child - 1) / 2;
while (parent > 0)
{
if (pHp->_hp[parent] < pHp->_hp[child])
{
Swap(pHp->_hp[parent], pHp->_hp[child]);
child = parent;
parent = (child - 1) / 2;
}
}
}
DataType Top(Heap* pHp)
{
return pHp->_hp[0];
}
void CheckCapacity(Heap* pHp)
{
assert(pHp);
int newcap = pHp->_capacity * 2;
if (pHp->_size > pHp->_capacity)
{
DataType *pnewcap = (DataType*)malloc(sizeof(pHp->_capacity) * 2);
assert(pnewcap);
memcpy(pnewcap, pHp->_hp, pHp->_size*sizeof(DataType));
free(pHp->_hp);
}
pHp->_capacity = newcap;
}
void Swap(int left, int right)
{
int t = left;
left = right;
right = t;
}
void HeapSort(Heap* pHp, int size)
{
int end = size - 1;
int root = (end-1) / 2;
for (; root >= 0; root--)
{
AdjustDown(pHp, root);
}
while (end > 1)
{
Swap(pHp->_hp[0], pHp->_hp[end]);
--end;
AdjustDown(pHp, pHp->_hp[0]);
}
}