- 存储结构
#include <stdio.h>
#include <stdlib.h>
#define ElementType int
typedef struct HeapNode
{
ElementType* data;
int size;//当前容量
int maxsize;//最大容量
}MaxHeap;
- 建堆
MaxHeap* CreatHeap(int MaxSize)
{
MaxHeap* H=(MaxHeap*)malloc(sizeof(HeapNode));
H->data=(ElementType*)malloc((MaxSize+1)*sizeof(ElementType));
H->maxsize=MaxSize;
H->size=0;
H->data[0]=1000;//哨兵
return H;
}
- 插入
bool IsFull(MaxHeap* Heap)
{
if(Heap->size==Heap->maxsize) return true;
return false;
}
void Insert(MaxHeap* Heap,ElementType x)
{
if(IsFull(Heap)==true){
printf("已满!");
return;
}
else
{
int i=++Heap->size;
for(;Heap->data[i/2]<x;i=i/2)// i/2是i的父结点
{
Heap->data[i]=Heap->data[i/2];
}
Heap->data[i]=x;
}
}
- 删除
bool IsEmpty(MaxHeap* Heap)
{
if(Heap->size==0) return true;
return false;
}
ElementType DeleteMax(MaxHeap* Heap)
{
if(IsEmpty(Heap)==true)
{
printf("已空\n");
return 0;
}
int max=Heap->data[1];//标记根结点即最大结点,用来返回
int parent,child;
int temp=Heap->data[Heap->size--];//标记最后一个元素
for(parent=1;2*parent<=Heap->size;parent=child)// 2*parent是parent的左孩子
{
child=2*parent;//先默认左孩子是大的
//有右孩子 && 右孩子大于左孩子
if(Heap->size!=child && Heap->data[child+1]>Heap->data[child]) child+=1;
if(temp>=Heap->data[child]) break;
else
{
Heap->data[parent]=Heap->data[child];
}
}
Heap->data[parent]=temp;
return max;
}
3.输出树
void Print(MaxHeap* Heap)
{
int i=1;
while(i<=Heap->size){
printf("%d ",Heap->data[i]);
i++;
}
printf("\n--------------------\n");
}