I am trying to implement an insert()
method for an arraylist-based heap implementation, but whenever I test the method inserting more than one integer where at least one of them is greater than ~4 the program takes forever to run. For example, stating heap.insert(1)
and heap.insert(8)
together in the main function will take forever to run. Here is my heap class:
import java.util.*;
public class Heap<E extends Comparable<E>> implements HeapAPI<E>
{
/**
* A complete tree stored in an array list representing this
* binary heap
*/
private ArrayList<E> tree;
/**
* Constructs an empty heap
*/
public Heap()
{
tree = new ArrayList<E>();
}
public boolean isEmpty()
{
return tree.isEmpty();
}
public void insert(E obj)
{
tree.add(tree.size(), obj);
siftUp(tree.size() - 1);
}
/**
* siftUp from position k. The key or node value at position
* may be greater that that of its parent at k/2.
* @param k position in the heap arraylist
*/
private void siftUp(int k)
{
E v = tree.get(k);
while (v.compareTo(tree.get(k / 2)) == 1)
{
tree.add(k, tree.get(k / 2));
k = k / 2;
}
tree.add(k, v);
}
public int size()
{
return tree.size();
}
}
This is the pseudocode given to us by my professor that I modeled the insert()
and siftUp()
methods from:
The program works for small integers, for example, if I type heap.insert(1)
a bunch of times in a row, but never finishes running if I change one of the numbers to a larger integer. No errors are thrown, as it doesn't finish executing when I try to run the program. I'm not sure what's going on. Any help is appreciated.