Advertisement
Bladtman

PriorityQueue

Mar 1st, 2012
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.19 KB | None | 0 0
  1. public class MaxPQ<Key extends Comparable<Key>> {
  2.     private Key[] pq;
  3.     private int N = 0;
  4.  
  5.     public MaxPQ (int max) {
  6.         pq = (Key[]) new Comparable[max+1]; //max+1 leaves one slot wasted memory, but saves a few calculations with every "step" taken through the three.
  7.     }
  8.  
  9.     public boolean isEmpty () {
  10.         return this.N==0;
  11.     }
  12.  
  13.     public int size (){
  14.         return this.N;
  15.     }
  16.  
  17.     public void insert (Key k) {
  18.         pq[++N] = k;
  19.         swim(N);
  20.     }
  21.  
  22.     public Key eatMax() {
  23.         Key max = pq[1];
  24.         swap(1, N);
  25.         pq[N--] = null;
  26.         drown(1);
  27.         return max;
  28.     }
  29.  
  30.     private boolean less (int i, int j) {
  31.         return pq[i].compareTo(pq[j]) < 0;
  32.     }
  33.  
  34.     private void swap (int i, int j) {
  35.         Key t = pq[i];
  36.         pq[i] = pq[j];
  37.         pq[j] = t;
  38.     }
  39.  
  40.     private void swim (int k) {
  41.         while (k>1 && less(k/2, k)) { //as long as my parents<me, swap me with my parents
  42.             swap(k/2, k);
  43.         }
  44.     }
  45.  
  46.     private void drown (int k) {
  47.         while (2*k <= N) {
  48.             int j = 2*k;
  49.             if (j<N && less(j, j+1)) j++;   //pick my bigest child!
  50.             if (!less(k, j)) break;     //if my biggest child<=me, we're done
  51.             swap(k, j);             //else swap me and my child
  52.             k=j;                //I get a second childhood!
  53.         }
  54.     }
  55.  
  56.     public Key[] getList() {
  57.         return pq;
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement