class PriorityQueue{
private Comparable[] array;
private int index;
public PriorityQueue(){
array=new Comparable[16];
index=0;
}
public boolean isEmpty(){
return index==0;
}
public void add(Comparable item){
if(index==array.length){
resize();
}
array[index]=item;
index++;
}
private void resize(){
Comparable[] newArray=new Comparable[array.length*2];
//we assume that the old array if full
for(int i=0;i<array.length;i++){
newArray[i]=array[i];
}
array=newArray;
}
public Comparable remove(){
if(index==0) return null;
int maxIndex=0;
//find the index of the item with the highest priority
for(int i=1;i<index;i++){
if(array[i].compareTo(array[maxindex])>0){
maxIndex=i;
}
}
Comparable result=array[maxindex];
//move the last item into the empty slot
index--;
array[maxindex]=array[index];
return result;
}
//无法掩饰对remove()的喜爱
}
//优先队列的数组实施
//高尔夫球手记分类
public class Golfer implements Comparable
{
String name;
int score;
public Golfer(String name,int score){
this.name=name;
this.score=score;
}
public int compareTo(Object obj){
Golfer that=(Golfer)obj;
int a=this.score;
int b=that.score;
//for golfers,low is good!
if(a<b) return 1;
if(a>b) return -1;
return 0;
}
public static void main(String args[]){
PriorityQueue pq=new PriorityQueue();
Integer item1=new Integer(2);
pq.add(item1);
Integer item2=new Integer(1);
pq.add(item2);
Integer item3=new Integer(3);
pq.add(item3);
while(!pq.isEmpty()){
Integer item=(Integer)pq.remove();
System.out.println(item);
}
Golfer tiger=new Golfer("Tiger Woods",61);
Golfer phil=new Golfer("Phil Mickelson",72);
Golfer hal=new Golfer("Hal Sutton",69);
pq.add(tiger);
pq.add(phil);
pq.add(hal);
while(!pq.isEmpty()){
Golfer golfer=(Golfer)pq.remove();
System.out.println(golfer.name+"\t"+golfer.score);
}
}
}