public class PrioQueue> { public Key[] pq; public int N; public PrioQueue(int cap) { pq = (Key[]) new Comparable[ cap + 1 ]; } public int size() { return N; } public boolean isEmpty() { return N == 0 ; } public void insert(Key key) { N++; // One more entry pq[N] = key; // Insert in left most open position filterUp(N); // Filter up.... } public Key peek() { return pq[1]; } public Key poll() { Key r = pq[1]; // Save return value exchange( 1, N ); // Exchange root with left most entry at lowest level N--; // One less entry filterDown(1); // Filter root node down return r; } /* ================================= helper functions =========== */ private void filterUp( int k ) { int parent; parent = k/2; while ( k > 1 /* not root */ && greater( parent, k) ) { exchange( k, parent ); // Exchange with parent k = parent; // Go up 1 level parent = k/2; // Update it's parent } } private void filterDown( int k ) { int c1, c2; while ( 2*k <= N ) { c1 = 2*k; // c1 = left child c2 = c1 + 1; // c2 = right child if ( c2 <= N && greater(c1, c2) ) c1 = c2; // c1 = smallest child if ( ! greater( k, c1 ) ) break; // In order, stop exchange(k, c1); // Exchange parent with smallest child k = c1; // Continue down the tree } } private boolean greater( int i, int j ) { return pq[i].compareTo(pq[j]) > 0 ; } private void exchange(int i, int j) { Key h; h = pq[i]; pq[i] = pq[j]; pq[j] = h; } /* ============================ Print */ void printPQ() { System.out.println("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv"); showR( 1, 0 ); System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"); } public void showR(int t, int h) { if (t > N) return; showR(2*t+1, h+1); printnode(t, h); showR(2*t, h+1); } public void printnode(int x, int h) { for (int i = 0; i < h; i++) System.out.print(" "); System.out.println("[" + pq[x] + "]"); } }