// Array based heap and priority queue import java.util.*; class PriorityQueue { private Comparable data[]; private int size; private int capacity; // constructors public PriorityQueue() { capacity = 100; size = 0; data = new Comparable[capacity]; } public PriorityQueue(int c) { capacity = c; size = 0; data = new Comparable[capacity]; } // required priority queue methods public void insert(Comparable x) { if (size >= capacity - 1) throw new RuntimeException("Full"); data[size++] = x; bubbleUp(size - 1); } public Comparable removeRoot() { if (size <= 0) throw new RuntimeException("Empty"); swapData(0, --size); bubbleDown(0); return data[size]; } // auxiliary utility methods private void swapData(int n, int m) { Comparable temp = data[n]; data[n] = data[m]; data[m] = temp; } private void bubbleUp(int n) { if (n <= 0) return; // at root Comparable dn = data[n]; Comparable dp = data[(n - 1)/2]; // parent data if (dn.compareTo(dp) >= 0) return; // no problems swapData(n, (n - 1)/2); bubbleUp((n - 1)/2); } public void bubbleDown(int n) { if (2*n + 1 >= size) return; // at leaf Comparable dn = data[n]; Comparable dl = data[2*n + 1]; // left child Comparable dr = dl; if (2 * n + 2 < size) dr = data[2*n + 2]; // right child if (dn.compareTo(dl) < 0 && dn.compareTo(dr) < 0) return; // no problems if (dr.compareTo(dl) < 0) { swapData(n, 2 * n + 2); bubbleDown(2*n + 2); } else { swapData(n, 2 * n + 1); bubbleDown(2*n + 1); } } // heap creation public void heapify(Iterator x) { while (x.hasNext()) { if (size + 1 == capacity) break; data[size++] = (Comparable) x.next(); } int n = size/2; while (--n >= 0) bubbleDown(n); if (x.hasNext()) throw new RuntimeException("Full"); } // menu driven program to test the heap implementation public static void main(String args[]) { PriorityQueue pq = new PriorityQueue(); boolean done = false; while (!done) { try { Scanner sc = new Scanner(System.in); System.out.println("\ncmds are + - Q: >>"); String cmd = sc.next(); String entry = null; char command = cmd.charAt(0); if (command == '+') entry = sc.next(); switch (cmd.charAt(0)) { case 'Q': done = true; break; case '+': pq.insert(entry); break; case '-': System.out.println(pq.removeRoot()); break; } } catch (Exception e) { System.out.println("Error " + e.toString()); } } } }