package com.tw.dst.sq;
/**
* <p>优先队列
* 优先队列允许访问最小(或者有时是最大)的数据项
优先队列的重要操作是有序地插入新数据项和移除关键字最小的数据项
* </p>
* @author tangw 2010-11-26
*
*/
public class PriorityQueue {
private int nItems; //队列中元素的个数
private long pqArr[];//队列数组
private int maxSize;//队列中最大元素个数
//构造函数
public PriorityQueue(int size){
maxSize = size;
pqArr = new long[size];
nItems = 0;
}
//插入排序
public void insert(long value){
int i;
if(nItems == 0)
pqArr[nItems++] = value;
else{
for(i = nItems-1;i >= 0;i--){
if(value < pqArr[i]){
pqArr[i+1] = pqArr[i];
}
else
break;
}
pqArr[i+1] = value;
nItems++;
}
}
//移除
public long remove(){
return pqArr[--nItems];
}
//是否为空
public boolean isEmpty(){
return nItems == 0;
}
//是否已满
public boolean isFull(){
return nItems == maxSize;
}
public void print(){
for(int i = 0;i < nItems;i++)
System.out.print(pqArr[i]+" ");
System.out.println();
}
public static void main(String[] args) {
PriorityQueue pq = new PriorityQueue(10);
while(!pq.isFull()){
long value = (long)(Math.random()*100);
pq.insert(value);
}
pq.print();
}
}