typedef struct HeapNode *Heap;
struct HeapNode {
ElementType *Data;
int Size;
int Capacity;
};
typedef Heap MaxHeap;
#define MAXDATA 100000;
MaxHeap CreateMaxHeap(
int MaxSize) {
MaxHeap H = (MaxHeap)
malloc(
sizeof(
struct HeapNode));
H->Data = (ElementType *)
malloc((MaxSize +
1) *
sizeof(ElementType));
H->Size =
0;
H->Capacity = MaxSize;
H->Data[
0] = MAXDATA;
return H;
}
int IsFull(MaxHeap H) {
return (H->Size == H->Capacity);
}
int IsEmpty(MaxHeap H) {
return (H->Size ==
0);
}
void InsertItem(MaxHeap H, ElementType Item) {
int position;
if (IsFull(H)) {
printf(
"最大堆已满,无法插入!\n");
return;
}
position = ++H->Size;
while ((position /=
2) && (H->Data[position /
2] < Item)) {
H->Data[position] = H->Data[position /
2];
}
H->Data[position] = Item;
return;
}
ElementType DeleteMax(MaxHeap H) {
int parent, child;
ElementType maxItem, temp;
if (IsEmpty(H)) {
printf(
"最大堆已为空!");
return -
1;
}
maxItem = H->Data[
1];
temp = H->Data[H->Size--];
for (parent =
1; parent *
2 <= H->Size; parent++) {
child = parent *
2;
if ((child != H->Size) && (H->Data[child] < H->Data[child +
1])) child++;
if (H->Data[child] > temp) H->Data[parent] = H->Data[child];
else break;
}
H->Data[parent] = temp;
return maxItem;
}
void PercDown(MaxHeap H,
int p)
{
int Parent, Child;
ElementType X;
X = H->Data[p];
for (Parent = p; Parent *
2 <= H->Size; Parent = Child) {
Child = Parent *
2;
if ((Child != H->Size) && (H->Data[Child]<H->Data[Child +
1]))
Child++;
if (X >= H->Data[Child])
break;
else
H->Data[Parent] = H->Data[Child];
}
H->Data[Parent] = X;
}
void BuildHeap(MaxHeap H)
{
int i;
for (i = H->Size /
2; i>
0; i--)
PercDown(H, i);
}