// Source code example for "A Practical Introduction // to Data Structures and Algorithm Analysis" // by Clifford A. Shaffer, Prentice Hall, 1998. // Copyright 1998 by Clifford A. Shaffer public class MinHeap{ // Min Heap class private Elem[] Heap; // Pointer to the heap array private int size; // Maximum size of the heap private int n; // Number of elements now in the heap public MinHeap(Elem[] h, int num, int max) // Constructor { Heap = h; n = num; size = max; buildheap(); } public int heapsize() // Return current size of the heap { return n; } public boolean isLeaf(int pos) // TRUE if pos is a leaf position { return (pos >= n/2) && (pos < n); } // Return position for left child of pos public int leftchild(int pos) { Assert.notFalse(pos < n/2, "Position has no left child"); return 2*pos + 1; } // Return position for right child of pos public int rightchild(int pos) { Assert.notFalse(pos < (n-1)/2, "Position has no right child"); return 2*pos + 2; } public int parent(int pos) { // Return position for parent Assert.notFalse(pos > 0, "Position has no parent"); return (pos-1)/2; } public void buildheap() // Heapify contents of Heap { for (int i=n/2-1; i>=0; i--) siftdown(i); } private void siftdown(int pos) { // Put element in its correct place Assert.notFalse((pos >= 0) && (pos < n), "Illegal heap position"); while (!isLeaf(pos)) { int j = leftchild(pos); if ((j<(n-1)) && (Heap[j].key() > Heap[j+1].key())) j++; // j is now index of child with greater value if (Heap[pos].key() <= Heap[j].key()) return; // Done DSutil.swap(Heap, pos, j); pos = j; // Move down } } public void insert(Elem val) { // Insert value into heap Assert.notFalse(n < size, "Heap is full"); int curr = n++; Heap[curr] = val; // Start at end of heap // Now sift up until curr's parent's > curr's key while ((curr!=0) && (Heap[curr].key() 0, "Removing from empty heap"); DSutil.swap(Heap, 0, --n); // Swap minimum with last value if (n != 0) // Not on last element siftdown(0); // Put new heap root val in correct place return Heap[n]; } // Remove value at specified position public Elem remove(int pos) { Assert.notFalse((pos > 0) && (pos < n), "Illegal heap position"); DSutil.swap(Heap, pos, --n); // Swap with last value if (n != 0) // Not on last element siftdown(pos); // Put new heap root val in correct place return Heap[n]; } } 