Code Fragment: HPQ2



template <typename Key, typename Element, typename Comp>
void HeapPriorityQueue<Key, Element, Comp>::
insertItem(const Key& k, const Element& e) {		// insert key-element
  Position z = T.add(Item(k, e));
  while (!T.isRoot(z)) {				// up-heap bubbling
    Position u = T.parent(z);
    if (comp(key(u), key(z)) <= 0) break;
    T.swapElements(u, z);
    z = u;
  }
}

template <typename Key, typename Element, typename Comp>
void HeapPriorityQueue<Key, Element, Comp>::
removeMin()						// remove minimum
    throw(EmptyContainerException) {
  if (isEmpty())
    throw EmptyContainerException("Removal from empty queue");
  if (size() == 1)
    T.remove();
  else {
    T.replaceElement(T.root(), T.remove());
    Position r = T.root();
    while (T.isInternal(T.leftChild(r))) { 		// down-heap bubbling
      Position s = T.rightChild(r);
      if (T.isExternal(T.rightChild(r)) ||
          comp(key(T.leftChild(r)), key(T.rightChild(r))) <= 0)
        s = T.leftChild(r);
      if (comp(key(s), key(r)) < 0) {
        T.swapElements(r, s);
        r = s;
      }
      else break;
    }
  }
}