-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathMinHeap.java
304 lines (244 loc) · 8.57 KB
/
MinHeap.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
package com.geeksforgeeks.heap;
import java.util.*;
@SuppressWarnings({"Duplicates", "SpellCheckingInspection"})
public class MinHeap<T> {
private int capacity = 10;
private int size = 0;
int[] items = new int[capacity];
private Map<Integer, Integer> itemPositionMap = new HashMap<>();
public class Node {
public int weight;
public T key;
public Node() {
}
public Node(int weight, T key) {
this.weight = weight;
this.key = key;
}
public String toString() {
return "Node : [weight : " + weight + ", key : " + key + "]";
}
}
private List<Node> allNodes = new ArrayList<>();
private Map<T, Integer> nodePositionMap = new HashMap<>();
public int getLeftChildIndex(int parentIndex) {
return 2 * parentIndex + 1;
}
public int getRightChildIndex(int parentIndex) {
return 2 * parentIndex + 2;
}
public int getParentIndex(int childIndex) {
return (childIndex - 1) / 2;
}
public boolean hasLeftChild(int index) {
return getLeftChildIndex(index) < size;
}
public boolean hasRightChild(int index) {
return getRightChildIndex(index) < size;
}
public boolean hasParent(int index) {
return getParentIndex(index) >= 0;
}
public int leftChild(int index) {
return items[getLeftChildIndex(index)];
}
public int rightChild(int index) {
return items[getRightChildIndex(index)];
}
public int parent(int index) {
return items[getParentIndex(index)];
}
public void swap(int indexOne, int indexTwo) {
// We have to swap the position in the MAP
itemPositionMap.put(items[indexOne], indexTwo);
itemPositionMap.put(items[indexTwo], indexOne);
int temp;
temp = items[indexOne];
items[indexOne] = items[indexTwo];
items[indexTwo] = temp;
}
public void ensureExtraCapacity() {
if (size == capacity) {
items = Arrays.copyOf(items, capacity * 2);
capacity *= 2;
}
}
/**
* This method will return the current position of item in the heap/(Array representing the heap)
*
* @param item
* @return
*/
public boolean contains(T item) {
return nodePositionMap.containsKey(item);
}
public Integer getWeight(T vertex) {
return allNodes.get(nodePositionMap.get(vertex)).weight;
}
/**
* This method will get the root, In case of Min Heap it's the minimum element in heap.
*
* @return
*/
public int peek() {
if (size == 0)
throw new IllegalStateException();
return items[0];
}
/**
* This method will extract the minimum element that is the root,
* and also re-heapify the heap
*
* @return
*/
public int extractMin() {
if (size == 0)
throw new IllegalStateException();
int item = items[0];
items[0] = items[size - 1];
size--;
nodePositionMap.remove(item);
heapifyDown();
return item;
}
public void add(int item) {
ensureExtraCapacity();
items[size] = item;
itemPositionMap.put(item, size);
size++;
heapifyUp();
}
public void heapifyUp() {
int index = size - 1;
while (hasParent(index) && parent(index) > items[index]) {
swap(getParentIndex(index), index);
index = getParentIndex(index);
}
}
private void heapifyDown() {
int index = 0;
while (hasLeftChild(index)) {
int smallerChildIndex = getLeftChildIndex(index);
if (hasRightChild(index) && rightChild(index) < items[smallerChildIndex]) {
smallerChildIndex = getRightChildIndex(index);
}
if (items[index] > items[smallerChildIndex]) {
swap(smallerChildIndex, index);
index = smallerChildIndex;
} else {
break;
}
}
}
public Node extractMinimumNode() {
Node node = allNodes.get(0);
Node lastNode = allNodes.get(size - 1);
allNodes.remove(node);
allNodes.remove(lastNode);
if ((size - 1) != 0) {
allNodes.add(0, lastNode);
size--;
nodePositionMap.remove(node.key);
nodePositionMap.put(lastNode.key, 0);
heapifyNodesDown();
}
return node;
}
private void heapifyNodesDown() {
int index = 0;
while (hasLeftChild(index)) {
int smallerChildIndex = getLeftChildIndex(index);
if (hasRightChild(index) && allNodes.get(getRightChildIndex(index)).weight < allNodes.get(smallerChildIndex).weight) {
smallerChildIndex = getRightChildIndex(index);
}
Node node = allNodes.get(index);
Node smallerChildNode = allNodes.get(smallerChildIndex);
if (node.weight > smallerChildNode.weight) {
swapNodes(index, smallerChildIndex);
index = smallerChildIndex;
} else {
break;
}
}
}
public void addNodeToHeap(int weight, T key) {
Node node = new Node(weight, key);
allNodes.add(node);
nodePositionMap.put(key, size);
size++;
heapifyNodesUp(size - 1);
}
public void printHeap() {
for (Node n : allNodes) {
System.out.println("[Wieght :: " + n.weight + ", KEY :: " + n.key + "]");
}
}
public void heapifyNodesUp(int index) {
while (hasParent(index) && allNodes.get(getParentIndex(index)).weight > allNodes.get(index).weight) {
swapNodes(getParentIndex(index), index);
index = getParentIndex(index);
}
}
private void swapNodes(int parentIndex, int currentNodeIndex) {
Node parentNode = allNodes.get(parentIndex);
Node currentNode = allNodes.get(currentNodeIndex);
nodePositionMap.put(parentNode.key, currentNodeIndex);
nodePositionMap.put(currentNode.key, parentIndex);
int weight = currentNode.weight;
T key = currentNode.key;
currentNode.weight = parentNode.weight;
currentNode.key = parentNode.key;
parentNode.weight = weight;
parentNode.key = key;
}
public void decreaseNodeWeight(T key, int newWeight) {
int position = nodePositionMap.get(key);
allNodes.get(position).weight = newWeight;
heapifyNodesUp(position);
}
public void printPositionMap() {
System.out.println(nodePositionMap);
}
/**
* Checks with heap is empty or not
*/
public boolean empty() {
return allNodes.size() == 0;
}
public static void main(String[] args) {
MinHeap minHeap = new MinHeap();
minHeap.add(10);
minHeap.add(15);
minHeap.add(20);
minHeap.add(17);
minHeap.add(25);
minHeap.add(5);
System.out.println("Initial Positions are ::==> " + minHeap.nodePositionMap);
System.out.println("Extracting the Minimum Element ::--> " + minHeap.extractMin());
System.out.println("After extracting the mininum element positions are :: ->" + minHeap.nodePositionMap);
System.out.println("Now Who is the minimum element ::--> " + minHeap.peek());
minHeap.add(1);
System.out.println("Now the minimum is ::-->" + minHeap.peek());
System.out.println("After adding 1 to the heap the positions are :: ->" + minHeap.nodePositionMap);
minHeap.extractMin();
System.out.println("Now the minimum is ::-->" + minHeap.peek());
System.out.println("After removing 1 from the heap the positions are :: ->" + minHeap.nodePositionMap);
System.out.println("==================== MIN HEAP FOR PRIMS ALGORITHM ======================");
MinHeap heap = new MinHeap<String>();
heap.size = 0;
heap.addNodeToHeap(3, "Tushar");
heap.addNodeToHeap(4, "Ani");
heap.addNodeToHeap(8, "Vijay");
heap.addNodeToHeap(10, "Pramila");
heap.addNodeToHeap(5, "Roy");
heap.addNodeToHeap(6, "NTF");
heap.addNodeToHeap(2, "AFR");
// heap.printHeap();
heap.printPositionMap();
System.out.println("Extracting Minimum Node " + heap.extractMinimumNode());
heap.printPositionMap();
heap.decreaseNodeWeight("Vijay", 1);
heap.printPositionMap();
System.out.println("Extract Minumum Node after decrease operation " + heap.extractMinimumNode());
}
}