1
1
package section18_Tries ;
2
2
3
3
import java .util .ArrayList ;
4
+ import java .util .HashMap ;
4
5
5
6
public class HeapGeneric <T extends Comparable <T >> {
6
7
7
8
ArrayList <T > data ;
8
9
boolean isMin ;
9
10
11
+ // this is used in Prim's algorithm implementation to track the order of
12
+ // insertion of item in Heap. Integer stores index of insertion.
13
+ HashMap <T , Integer > insertOrderMap = new HashMap <>();
14
+
10
15
public HeapGeneric () {
11
16
this (false );
12
17
}
@@ -34,6 +39,8 @@ public T get() {
34
39
35
40
public void add (T item ) {
36
41
data .add (item );
42
+ // store item insertion index in hashmap
43
+ insertOrderMap .put (item , data .size () - 1 );
37
44
upheapify (data .size () - 1 );
38
45
}
39
46
@@ -52,6 +59,10 @@ private void swap(int i, int j) {
52
59
53
60
data .set (i , jthVal );
54
61
data .set (j , ithVal );
62
+
63
+ // update: for prims' use case
64
+ insertOrderMap .put (ithVal , j );
65
+ insertOrderMap .put (jthVal , i );
55
66
}
56
67
57
68
public T remove () throws Exception {
@@ -65,6 +76,9 @@ public T remove() throws Exception {
65
76
66
77
downheapify (0 );
67
78
79
+ // update - removed from index hashmap
80
+ insertOrderMap .remove (removedItem );
81
+
68
82
return removedItem ;
69
83
}
70
84
@@ -89,4 +103,13 @@ public void downheapify(int pi) {
89
103
public int isLarger (T thisRef , T otherRef ) {
90
104
return thisRef .compareTo (otherRef );
91
105
}
106
+
107
+ // Prims' usecase
108
+ public void updatePriority (T pair ) {
109
+ int pairIndex = insertOrderMap .get (pair );
110
+
111
+ // since new cost of Pair is less than old cost we call upheapify here
112
+ upheapify (pairIndex );
113
+ }
114
+
92
115
}
0 commit comments