堆:优先队列(Priority Queue),特殊的队列,取出元素的顺序是按照元素的优先权(关键字)大小,而不是元素进入队列的先后顺序。
用完全二叉树来表示堆
从根结点到任意结点路径上结点序列的有序性
类型名称:最大堆(MaxHeap)
数据对象集:完全二叉树,每个结点的元素值不小于其子结点的元素值
typedef struct HNode *Heap;//堆的类型定义
struct HNode{
ElementType *Data;
int Size;
int Capacity;
};
typedef Heap MaxHeap;//最大堆
typedef Heap MinHeap;//最小堆
#define MAXDATA 1000;
MaxHeap CreateHeap(int MaxSize)
{
MaxHeap H = (MaxHeap)malloc(sizeof(struct HNode));
H->Data = (ElementType *)malloc((MaxSize+1)*sizeof(ElementType));
H->Size = 0;
H->Capacity = MaxSize;
H->Data[0] = MAXDATA;
return H;
}
bool IsFull(MaxHeap H)
{
return (H->Size == H->Capacity);
}
bool Insert(MaxHeap H,ElementType X)
{
int i;
if(IsFull){
printf("最大堆已满");
return false;
}
i = ++H->Size;
for(;H->Data[i/2 < X;i/2])
H->Data[i] = H->Data[i/2];
H->Data[i] = X;
return true;
}
#define ERROR -1
bool IsEmpty(MaxHeap H)
{
return (H->Size == 0);
}
ElementType DeleteMax(MaxHeap H)
{
int Parent,Child;
ElementType MaxItem,X;
if(IsEmpty(H)){
printf("最大堆已为空");
return ERROR;
}
MaxItem = H->Data[1];
X = H->Data[H->Size--];
for(Parent=1;Parent*2<=H->Size;Parent=Child)
}