/*************************************************************************** * Helper functions to restore the heap invariant. ***************************************************************************/ private void swim(int k) { while (k > 1 && OrderHelper.Lesser <Key>(pq[k / 2], pq[k])) { OrderHelper.Exch(pq, k, k / 2); k = k / 2; } }
private void sink(int k) { while (2 * k <= N) { int j = 2 * k; if (j < N && OrderHelper.Lesser <Key>(pq[j], pq[j + 1])) { j++; } if (!OrderHelper.Lesser <Key>(pq[k], pq[j])) { break; } OrderHelper.Exch(pq, k, j); k = j; } }
// is subtree of pq[1..N] rooted at k a min heap? private bool isMaxHeap(int k) { if (k > N) { return(true); } int left = 2 * k, right = 2 * k + 1; if (left <= N && OrderHelper.Lesser <Key>(pq[k], pq[left])) { return(false); } if (right <= N && OrderHelper.Lesser <Key>(pq[k], pq[right])) { return(false); } return(isMaxHeap(left) && isMaxHeap(right)); }