Skip to content

Commit 1c3a2b1

Browse files
committed
update: added methods to be used by Prims algorithm in package section20_Graph
1 parent a8d1c72 commit 1c3a2b1

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

Interview Prep/section18_Tries/HeapGeneric.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,17 @@
11
package section18_Tries;
22

33
import java.util.ArrayList;
4+
import java.util.HashMap;
45

56
public class HeapGeneric<T extends Comparable<T>> {
67

78
ArrayList<T> data;
89
boolean isMin;
910

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+
1015
public HeapGeneric() {
1116
this(false);
1217
}
@@ -34,6 +39,8 @@ public T get() {
3439

3540
public void add(T item) {
3641
data.add(item);
42+
// store item insertion index in hashmap
43+
insertOrderMap.put(item, data.size() - 1);
3744
upheapify(data.size() - 1);
3845
}
3946

@@ -52,6 +59,10 @@ private void swap(int i, int j) {
5259

5360
data.set(i, jthVal);
5461
data.set(j, ithVal);
62+
63+
// update: for prims' use case
64+
insertOrderMap.put(ithVal, j);
65+
insertOrderMap.put(jthVal, i);
5566
}
5667

5768
public T remove() throws Exception {
@@ -65,6 +76,9 @@ public T remove() throws Exception {
6576

6677
downheapify(0);
6778

79+
// update - removed from index hashmap
80+
insertOrderMap.remove(removedItem);
81+
6882
return removedItem;
6983
}
7084

@@ -89,4 +103,13 @@ public void downheapify(int pi) {
89103
public int isLarger(T thisRef, T otherRef) {
90104
return thisRef.compareTo(otherRef);
91105
}
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+
92115
}

0 commit comments

Comments
 (0)