优先队列利用堆实现,堆的实现在前面已经说过了,优先队列的一个重要的操作是:
1. heap_max O(1)
2. heap_extract_max O(lgn)
3. heap_increase_key O(lgn)
4, heap_insert O(lgn)
下面是C语言实现
#define MIN -100000
int heap_max(struct heap *h)
{
return h->arr[1];
}
int heap_extract_max(struct heap *h)
{
int max = h->arr[1];
h->arr[1] = h->arr[h->size];
h->size--;
max_heapify(h, 1);
return max;
}
void heap_increase_key(struct heap *h, int pos, int key)
{
if (h->arr[pos] < key) {
h->arr[pos] = key;
while (pos > 1 && h->arr[pos] > h->arr[pos / 2]) {
swap(&(h->arr[pos]), &(h->arr[pos / 2]));
pos /= 2;
}
}
}
void heap_insert(struct heap * h, int key)
{
//将最后一个元素后的元素设为无穷小,然后增加其键值
h->arr[++(h->size)] = MIN;
heap_increase_key(h, h->size, key);
}