11.07.2015 Views

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

174 Chap. 5 Binary Trees/** Heapify contents of Heap */public void buildheap(){ for (int i=n/2-1; i>=0; i--) siftdown(i); }/** Put element in its correct place */priv<strong>at</strong>e void siftdown(int pos) {assert (pos >= 0) && (pos < n) : "Illegal heap position";while (!isLeaf(pos)) {int j = leftchild(pos);if ((j= 0) return;DSutil.swap(Heap, pos, j);pos = j; // Move down}}/** Remove <strong>and</strong> return maximum value */public E removemax() {assert n > 0 : "Removing from empty heap";DSutil.swap(Heap, 0, --n); // Swap maximum with last valueif (n != 0) // Not on last elementsiftdown(0); // Put new heap root val in correct placereturn Heap[n];}/** Remove <strong>and</strong> return element <strong>at</strong> specified position */public E remove(int pos) {assert (pos >= 0) && (pos < n) : "Illegal heap position";if (pos == (n-1)) n--; // Last element, no work to be doneelse{DSutil.swap(Heap, pos, --n); // Swap with last value// If we just swapped in a big value, push it upwhile ((pos > 0) &&(Heap[pos].compareTo(Heap[parent(pos)]) > 0)) {DSutil.swap(Heap, pos, parent(pos));pos = parent(pos);}if (n != 0) siftdown(pos); // If it is little, push down}return Heap[n];}}Figure 5.19 (continued)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!