class PriorityQueue {
private ArrayList maxHeap;
public PriorityQueue () {
maxHeap = new ArrayList();
maxHeap.add(null); //to fill element 0
}
public boolean empty () {
return maxHeap.size() == 1;
}
public void insert (Comparable p) {
if (p==null) return;
maxHeap.add(p);
int index = maxHeap.size()-1;
swapWithParent(index);
}
private void swapWithParent(int index)
{
int parentindex = index/2;
if (parentindex==0) return;
if (p.compareTo(maxHeap.get(parentindex)) > 0)
{
//swap them
Comparable p = maxHeap.get(index);
maxHeap.set(index,maxHeap.get(parentindex));
maxHeap.set(parentindex,p);
swapWithParent(parentindex);
}
}
}
Sunday, December 21, 2008
Priority Queue in Java using ArrayList
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment