一、优先队列不同于普通队列采用先进先出的队列元素存取方式。插入队列元素时按照一定的规则插入,每次都是取队列中优先级最高的元素。在操作系统中,调度程序必须决定在什么时候运行哪个进程。一般来说,短的作业是需要尽可能快地完成,也就是说,短的作业应该拥有优先权。这种特殊的应用将由一种特殊的队列来完成,这种数据结构叫做优先队列。
二、最基本的两种操作
优先队列具备的最基本的两种操作,是插入和删除最小者。插入操作相当于入列,而删除操作相当于出队。只是这里有一些地方是不同的,不像之前出队和入队操作那么简单。
三、二叉堆
一般来说,管二叉堆叫堆,它的应用非常普遍。而堆就是一棵完全二叉树。这种数据结构有一个特点,就是存储它的元素可以用数组来存储,不必动用指针。对于数组中任意一个位置i上面的元素,它的左儿子在位置2i上,右儿子在(2i + 1)上;父节点则在位置(i/2)上。
堆序的另外一个特性,就是每一个节点X,X的父亲中关键字小于或者等于X,根节点例外,因为根节点并没有父节点。
在优先队列的里面,会用到 堆排序。
//优先队列 c++实现
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
template <class Type>
class Priority_Queue
{
private:
Type *HeapArray;
int CurrentSize; //队列当前元素个数
int MaxSize; //队列总大小
public:
Priority_Queue(int n=100);
bool DoubleSpace(); //再次分配空间函数
bool HeapAdjust(int s,int n); //堆调整函数
bool BuildHeap(); //建堆函数
bool Empty(); //队列空判断函数
bool pop(); //出队函数
bool push(Type x); //入队函数
Type top(); //队列首元素
virtual ~Priority_Queue();
};
template <class Type>
Priority_Queue<Type>::Priority_Queue(int n)
{
HeapArray=new Type[n+1];
CurrentSize=0;
MaxSize=n;
}
template <class Type>
bool Priority_Queue<Type>::DoubleSpace()
{
HeapArray=(Type*)realloc(HeapArray,sizeof(Type)*2*(MaxSize+1));
if(HeapArray==NULL)
{
return false;
}
MaxSize*=2;
return true;
}
template <class Type>
bool Priority_Queue<Type>::HeapAdjust(int s,int n)//堆调整
{
Type temp=HeapArray[s];
for (int j=2*s; j<=n; j*=2) //从最后一个具有孩子结点开始一次向上调整
{
if(j<n && HeapArray[j]<HeapArray[j+1])
{
j++;
}
if(temp>=HeapArray[j])
{
break;
}
HeapArray[s]=HeapArray[j];
s=j;
}
HeapArray[s]=temp;
return true;
}
template <class Type>
bool Priority_Queue<Type>::BuildHeap() //建堆
{
for (int i=CurrentSize/2; i>=1; i--)
{
HeapAdjust(i, CurrentSize);
}
for (int i=CurrentSize; i>1; i--)
{
swap(HeapArray[1], HeapArray[i]);
HeapAdjust(1, i-1);
}
return true;
}
template <class Type>
bool Priority_Queue<Type>::Empty() //判空
{
if(CurrentSize==0)
{
return true;
}
return false;
}
template <class Type>
bool Priority_Queue<Type>::pop() //出队
{
swap(HeapArray[1], HeapArray[CurrentSize]); //与最后一个元素交换
CurrentSize--; //个数减少
BuildHeap(); //重新调整堆
return true;
}
template <class Type>
bool Priority_Queue<Type>::push(Type x) //入队
{
if(CurrentSize==MaxSize)
{
if(!DoubleSpace())
{
return false;
}
}
HeapArray[++CurrentSize]=x;
return true;
}
template <class Type>
Type Priority_Queue<Type>::top() //返回根结点
{
return HeapArray[1];
}
template <class Type>
Priority_Queue<Type>::~Priority_Queue<Type>() //析构函数
{
delete HeapArray;
CurrentSize=0;
HeapArray=NULL;
}
int main()
{
Priority_Queue<int>q;
srand(time(NULL));
for (int i=110; i>=1; i--)
{
q.push(rand()%90+1); //1-90的随机数
}
q.BuildHeap();
while (!q.Empty())
{
printf("%d ",q.top());
q.pop();
}
return 0;
}