优先级队列
优先级队列是比栈和队列更专用的数据结构,但是他在很多情况下都很有用,像普通队列一样,优先级队列有一个队头和一个队尾,并且也是从队头移除数据项,不过在优先级队列中,数据项按关键字的值有序,这样关键字最小的数据项(或者在某些实现中是关键字最大的数据项)总是在队头,数据项插入的时候会按照顺序插入到合适的位置确保队列的顺序。
像栈和队列一样,优先级队列在某些计算机系统中也有很多应用,优先级队列也经常用作程序员编程的工具,例如在图的最小生成树算法中应用优先级队列。
优先级队列的java代码
// priorityQ.java
// demonstrates priority queue
// to run this program: C>java PriorityQApp
class PriorityQ
{
// array in sorted order, from max at 0 to min at size-1
private int maxSize;
private long[] queArray;
private int nItems;
//-------------------------------------------------------------
public PriorityQ(int s) // constructor
{
maxSize = s;
queArray = new long[maxSize];
nItems = 0;
}
//-------------------------------------------------------------
public void insert(long item) // insert item
{
int j;
if(nItems==0) // if no items,
queArray[nItems++] = item; // insert at 0
else // if items,
{
for(j=nItems-1; j>=0; j--) // start at end,
{
if( item > queArray[j] ) // if new item larger,
queArray[j+1] = queArray[j]; // shift upward
else // if smaller,
break; // done shifting
} // end for
queArray[j+1] = item; // insert it
nItems++;
} // end else (nItems > 0)
} // end insert()
//-------------------------------------------------------------
public long remove() // remove minimum item
{ return queArray[--nItems]; }
//-------------------------------------------------------------
public long peekMin() // peek at minimum item
{ return queArray[nItems-1]; }
//-------------------------------------------------------------
public boolean isEmpty() // true if queue is empty
{ return (nItems==0); }
//-------------------------------------------------------------
public boolean isFull() // true if queue is full
{ return (nItems == maxSize); }
//-------------------------------------------------------------
} // end class PriorityQ
class PriorityQApp
{
public static void main(String[] args)
{
PriorityQ thePQ = new PriorityQ(5);
thePQ.insert(30);
thePQ.insert(50);
thePQ.insert(10);
thePQ.insert(40);
thePQ.insert(20);
while( !thePQ.isEmpty() )
{
long item = thePQ.remove();
System.out.print(item + " "); // 10, 20, 30, 40, 50
} // end while
System.out.println("");
} // end main()
//-------------------------------------------------------------
} // end class PriorityQApp
说明:在此优先级队列中,最大的数总是在数组下标为0的位置,最小的数总是在数组下标最大的位置。
优先级队列的效率
在优先级队列中,插入操作需要O(N)的时间,而删除操作则需要O(1)的时间,后续将介绍如何通过堆来改进插入操作的时间。