I have an array representation that holds a max heap. For an array of ‘d’,’b’,’c’ it’s holding : b, d, c although it is supposed to be b, c, d. This is my add method:
public boolean add (E e) {
ensureCapacity(objectCount + 1);
pq[objectCount++] = e;
//percolate up
for (int i = objectCount - 1; i >= 0; i--) {
if (priorityComparator.compare(pq[i], pq[parent(i)]) >= 0) {
E tmp = pq[parent(i)];
pq[parent(i)] = pq[i];
pq[i] = tmp;
}
}
modCount++;
return true;
}
If I add ‘a’ next it changes successfully to a,b,c,d. How can I fix the method so that it check the left child (2*i+1) and right child(2*i+2) and swaps their values according to which has the higher priority queue (a has higher priority than b, etc)?
I think you have a MIN heap and not a MAX heap.
I haven’t looked at your code but:
A min heap guarantees the following:
The output b, d, c is perfectly legit in your case. Try removing b and call heapify again, the output will be c, d.
Wiki link: http://en.wikipedia.org/wiki/Binary_heap
EDIT:
If in your case you consider giving ‘a’ a higher priority than ‘b’, then yes, you do have a MAX heap.