/** * Initializes a priority queue from the array of keys. Takes time proportional to the number of * keys, using sink-based heap construction. * * @param keys the array of keys */ public MinPQ(Key[] keys) { N = keys.length; pq = (Key[]) new Object[keys.length + 1]; for (int i = 0; i < N; i++) pq[i + 1] = keys[i]; for (int k = N / 2; k >= 1; k--) sink(k); assert isMinHeap(); }
/** * Removes and returns a smallest key on the priority queue. * * @return a smallest key on the priority queue * @throws java.util.NoSuchElementException if the priority queue is empty */ public Key delMin() { if (isEmpty()) throw new NoSuchElementException("Priority queue underflow"); exch(1, N); Key min = pq[N--]; sink(1); pq[N + 1] = null; // avoid loitering and help with garbage collection if ((N > 0) && (N == (pq.length - 1) / 4)) resize(pq.length / 2); assert isMinHeap(); return min; }