二叉堆優先佇列

壹頁書發表於2016-09-22


  1. public class MaxPQ <Key extends Comparable<Key>> {
  2.     private Key[] pq;
  3.     private int N=0;
  4.     public MaxPQ(int maxN){
  5.         pq=(Key[])new Comparable[maxN+1];
  6.     }

  7.     public boolean isEmpty(){
  8.         return N==0;
  9.     }

  10.     public int size(){
  11.         return N;
  12.     }

  13.     public void insert(Key v){
  14.         pq[++N]=v;
  15.         swim(N);
  16.     }

  17.     private void swim(int k) {
  18.         while(k>1 && less(k/2,k)){
  19.             exch(k/2,k);
  20.             k=k/2;
  21.         }
  22.     }

  23.     private boolean less(int i, int j) {
  24.         return pq[i].compareTo(pq[j])<0;
  25.     }

  26.     public Key delMax(){
  27.         Key max=pq[1] ;
  28.         exch(1,N--);
  29.         pq[N+1]=null;
  30.         sink(1);
  31.         return max;
  32.     }

  33.     private void sink(int k) {
  34.         while(2*k<=N){
  35.             int j=2*k;
  36.             if(j<N && less(j,j+1))
  37.                 j++;
  38.             if(!less(k,j))
  39.                 break;
  40.             exch(k,j);
  41.             k=j;
  42.         }
  43.     }

  44.     private void exch(int i, int j) {
  45.         Key t=pq[i];
  46.         pq[i]=pq[j];
  47.         pq[j]=t;
  48.     }

  49.     public static void main(String[] args){
  50.         Integer[] data={100,20,21,28,22,26,80,33,3,2,9,8,7,10,77,66,99,96,91,94};

  51.         MaxPQ<Integer> pq=new MaxPQ<>(data.length);
  52.         for(int i=0;i<data.length;i++){
  53.             pq.insert(data[i]);
  54.         }
  55.         while(!pq.isEmpty()){
  56.             System.out.println(pq.delMax());
  57.         }
  58.     }
  59. }

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29254281/viewspace-2125325/,如需轉載,請註明出處,否則將追究法律責任。

相關文章