优先级队列可以用堆表示。在一个给定的作业调度或者基于事件驱动的模型中,优先级队列的元素对应着应用中的对象。通常,我们需要确定一个给定的队列中元素所对应的应用对象。当用堆来实现优先级队列时,需要在堆中的每个元素里存储对应应用对象的柄(handle)。下面讨论如何实现基于堆的最大优先级队列。
#include <iostream>
using namespace std;
int size=0;
void Maxheapify(int A[],int i){
int left=2*i,right=2*i+1,largest;
if (left<=size&&A[left]>A[i])
{
largest=left;
}
else
{
largest=i;
}
if (right<=size&&A[right]>A[largest])
{
largest=right;
}
if (largest!=i)
{
int temp=A[i];
A[i]=A[largest];
A[largest]=temp;
Maxheapify(A,largest);
}
}
/*从堆中取出最大值*/
int HeapMax(int A[]){
if (size<1)
{
return 0;
}
int max=A[1];
A[1]=A[size-1];
Maxheapify(A,1);
return max;
}
/*堆插入*/
void Heapinsert(int A[],int key){
int i=++size,temp;
A[i]=key;
while (i>1&&A[i/2]<A[i])
{
temp=A[i];
A[i]=A[i/2];
A[i/2]=temp;
i=i/2;
}
}
int main(){
int A[11];
Heapinsert(A,5);
Heapinsert(A,1);
Heapinsert(A,8);
Heapinsert(A,10);
for (int i=1;i<=4;i++)
{
cout<<A[i]<<endl;
}
return 0;
}