`
keating
  • 浏览: 166976 次
  • 性别: Icon_minigender_1
  • 来自: weihai
社区版块
存档分类
最新评论

很好很强大的优先队列

 
阅读更多
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);
		}  

	}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics