LAB E - return value; } public int getParent( int num) {...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
import java.util.*; public class minHeap<T extends Comparable<? super T>> { int [] Heap ; int MAX_SIZE , lastIndex ; public minHeap ( int max) { MAX_SIZE = max; Heap = new int [ MAX_SIZE ]; lastIndex = 0 ; Heap [0] = Integer. MIN_VALUE ; } public void add(T newEntry){ lastIndex ++; Heap [ lastIndex ] = (Integer) newEntry; int current = lastIndex ; while ( Heap [current] < Heap [getParent(current)]) { makeSwap(current, getParent(current)); current = getParent(current); } } public int removeMin() { makeSwap(1, lastIndex ); lastIndex --; if ( lastIndex != 0) reheap(1); return Heap [ lastIndex +1]; } private void reheap( int pos) { int minChild; while (!checkLeaf(pos)) { minChild = getLeftChild(pos); if ((minChild < lastIndex Heap [minChild] > Heap [minChild+1])) minChild++; if ( Heap [pos] <= Heap [minChild]) break ; makeSwap(pos,minChild); pos = minChild; } } public int getLeftChild( int num){ int value = 2*num; return value; } public int getRightChild( int num) { int value = 2*num + 1;
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: return value; } public int getParent( int num) { int value = num /2; return value; } public boolean isEmpty(){ return lastIndex &lt; 1; } public boolean checkLeaf ( int value) { return ((value &gt; lastIndex /2) &amp;&amp; (value &lt;= lastIndex )); } public void makeSwap( int p1, int p2) { int tmp; tmp = Heap [p1]; Heap [p1] = Heap [p2]; Heap [p2] = tmp; } } public class minHeapTest&lt;T extends minHeap&lt;?&gt; &gt; { public static void main(String args) { minHeap&lt;Integer&gt; heap = new minHeap&lt;Integer&gt;(10); System. out .println( &quot;* START *&quot; ); heap.add(1); heap.add(7); heap.add(5); heap.add(3); heap.add(4); int sum = 0; while (!heap.isEmpty()) { sum += heap.removeMin(); } System. out .println( &quot;* What is the sum? *&quot; + sum + &quot;*&quot; ); System. out .println( &quot;* END OF THE TEST *&quot; ); } }...
View Full Document

This note was uploaded on 01/23/2012 for the course CS 111C taught by Professor Metzler during the Spring '11 term at City College of San Francisco.

Page1 / 2

LAB E - return value; } public int getParent( int num) {...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online