很好很强大的优先队列

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

}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值