@ -55,12 +55,14 @@ public class HeapPQ<K,V> extends AbstractPriorityQueue<K,V> {
@@ -55,12 +55,14 @@ public class HeapPQ<K,V> extends AbstractPriorityQueue<K,V> {
// Utility:
// swap
protectedvoidswap(inti,intj){
Item<K,V>temp=heap.get(i);
heap.set(i,heap.get(j));
heap.set(j,temp);
}
// upheap
protectedvoidupheap(intj){
// j==0 is root
while(j>0){
@ -73,7 +75,19 @@ public class HeapPQ<K,V> extends AbstractPriorityQueue<K,V> {
@@ -73,7 +75,19 @@ public class HeapPQ<K,V> extends AbstractPriorityQueue<K,V> {
}
}
// recursive upheap
protectedvoidupheap_r(intj){
// now check for recursive case
intp=parent(j);
if(compare(heap.get(j),heap.get(p))<0){
swap(j,p);
self.upheap_r(parent);
}
// else base case, return nothing
}
// downheap
protectedvoiddownheap(intj){
while(hasLeft((j))){
intleftIndex=left(j);
@ -94,11 +108,36 @@ public class HeapPQ<K,V> extends AbstractPriorityQueue<K,V> {
@@ -94,11 +108,36 @@ public class HeapPQ<K,V> extends AbstractPriorityQueue<K,V> {
}
}
// recursive downheap
protectedvoiddownheap_r(intj){
if(hasLeft(j)){
intleftIndex=left(j);
// assume left child is smaller
intsmallChildIndex=leftIndex;
// if right child exists, check if right child is smaller
@ -106,6 +145,7 @@ public class HeapPQ<K,V> extends AbstractPriorityQueue<K,V> {
@@ -106,6 +145,7 @@ public class HeapPQ<K,V> extends AbstractPriorityQueue<K,V> {
upheap(heap.size()-1);// upheap the newest entry (last item in array)
}
// remove min
publicVremoveMin(){
if(heap.isEmpty()){
thrownewEmpty();
@ -120,14 +160,6 @@ public class HeapPQ<K,V> extends AbstractPriorityQueue<K,V> {
@@ -120,14 +160,6 @@ public class HeapPQ<K,V> extends AbstractPriorityQueue<K,V> {
returnexpunge.getValue();// return the value of the item we grabbed before removing.
}
// Required by priority queue interface:
publicintsize(){
returnheap.size();
}
publicVpeekMin(){
if(heap.isEmpty()){
thrownewEmpty();
@ -137,6 +169,14 @@ public class HeapPQ<K,V> extends AbstractPriorityQueue<K,V> {
@@ -137,6 +169,14 @@ public class HeapPQ<K,V> extends AbstractPriorityQueue<K,V> {
// Priority queue interface:
// get size
publicintsize(){
returnheap.size();
}
// protected iterator class for making this class iterable (PriorityQueue extends Iterable)
protectedclassItemIteratorimplementsIterator<K>{
Iterator<Item<K,V>>it;
publicItemIterator(){
@ -153,6 +193,10 @@ public class HeapPQ<K,V> extends AbstractPriorityQueue<K,V> {
@@ -153,6 +193,10 @@ public class HeapPQ<K,V> extends AbstractPriorityQueue<K,V> {