I am learning to use heaps and as an exercise I am trying to write a program using a heap class I have created to sort words. I have read in words from a file and added them to the heap successfully. I am having some trouble figuring out how I can print out a sorted list of the words. From my understanding of how a min-heap works, if I remove from the min/root node they will always be removed in sorted order. So far I have tried out to do a simple for loop but, only half of the heap is being removed.
My Main Attempt
public static void main(String[] args) {
Heap heap = new Heap();
heap = read( heap );
for( int i = 0; i < heap.getSize(); i++){
heap.removeMin();
}
heap.printHeap();
}
This is the remove function in my Heap Class
public Node removeMin(){
Node min = heap.get(0);
int index = heap.size() - 1;
Node last = heap.remove(index);
if( index > 0 ){
heap.set( 0, last );
Node root = heap.get(0);
int end = heap.size() - 1;
index = 0;
boolean done = false;
while(!done){
if(getLCLoc(index) <= end ){
//left exists
Node child = getNodeAt( getLCLoc(index) );
int childLoc = getLCLoc(index);
if( getRCLoc(index) <= end ){
//right exists
if( getNodeAt( getRCLoc(index) ).getData().compareToIgnoreCase( child.getData() ) < 0 ){
child = getNodeAt( getRCLoc(index) );
childLoc = getRCLoc(index);
}
}
if(child.getData().compareToIgnoreCase( root.getData() ) < 0 ){
heap.set( index, child );
index = childLoc;
}else{
done = true;
}
}else{
//no children
done = true;
}
}
heap.set( index, root );
}
return min;
}
I would guess that remove()
decreases heap size by 1. So, for each iteration of your loop, you are incrementing i
by 1 and decrementing heap size by 1. I would change to a while loop that runs while heapsize >0.