一.概念
优先队列(Priority Queue):特殊的“队列”,取出元素的顺序是依照元素的优先权(关键字)大小,而不是元素进入队列的先后顺序
二.优先队列完全二叉树表示
堆的两个特性
- 结构性:用数组表示完全二叉树
- 有序性:任一结点的关键字是其子树所有结点的最大值(或最小值) 最大堆(MaxHeap) 最小堆(MinHeap)
- 从根结点到任意结点路径上结点序列的有序性
三.最大堆代码实现(数组实现)
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define ElementType int
typedef struct MAXHEAP
{
ElementType *data;
int size;
int Capacity;
} MaxHeap;
MaxHeap *Create(int MaxSize)
{
MaxHeap *H = (MaxHeap *)malloc(sizeof(MaxHeap));
H->data = (ElementType *)malloc(sizeof(ElementType) * (MaxSize + 1));
H->size = 0;
H->Capacity = MaxSize;
H->data[0] = INT_MAX;
return H;
}
bool isFull(MaxHeap *heap)
{
return heap->size == heap->Capacity;
}
bool isEmpty(MaxHeap *heap)
{
return heap->size == 0;
}
void Insert(MaxHeap *heap, ElementType item)
{
if (isFull(heap))
{
return;
}
int i = ++heap->size;
while (heap->data[i / 2] < item)
{
heap->data[i] = heap->data[i / 2];
i /= 2;
}
heap->data[i] = item;
}
ElementType DeleteMax(MaxHeap *heap)
{
ElementType Maxitem = heap->data[1];
ElementType temp = heap->data[heap->size--];
int parent, child;
for (parent = 1; parent * 2 <= heap->size; parent = child)
{
child = parent * 2;
if (child != heap->size && heap->data[child] < heap->data[child + 1])
{
child = child + 1;
}
if (temp >= heap->data[child])
break;
else
heap->data[parent] = heap->data[child];
}
heap->data[parent] = temp;
return Maxitem;
}