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; }