-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathMinHeap.java
More file actions
96 lines (80 loc) · 2.7 KB
/
MinHeap.java
File metadata and controls
96 lines (80 loc) · 2.7 KB
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
// Time complexity : Insert (O(log n)), Peek (O(1)), ExtractMin (O(log n))
// Space complexity : O(1)
public class MinHeap {
private static Integer MAX_SIZE = 1000;
private final Integer[] heap = new Integer[MAX_SIZE];
private Integer size = 0;
MinHeap() {}
// Add the element to the end and bubble it up to the correct position
public void insert(Integer element) {
if (size.equals(MAX_SIZE)) return;
heap[size] = element;
heapifyUp(size-1);
size++;
}
private void heapifyUp(int index) {
while(index > 0){
Integer parentIndex = getParentIndex(index);
if (parentIndex == null) break;
if(heap[parentIndex] > heap[index]){
swap(parentIndex, index);
index = parentIndex;
}else{
break;
}
}
}
// Remove the element to the first and copy the last element to the root.
// Shift down the root value by comparing with its child.
public Integer extractMin() {
if (size == 0) return null;
int minValue = heap[0];
// Check if heap has elements
if(size > 0) {
heap[0] = heap[size - 1];
heapifyDown(0);
}
size--;
return minValue;
}
private void heapifyDown(int index) {
int smallest = index;
while (true) {
Integer leftChildIndex = getLeftChild(index);
if (leftChildIndex < size && heap[leftChildIndex] < heap[smallest]) {
smallest = leftChildIndex;
}
Integer rightChildIndex = getRightChild(index);
if (rightChildIndex < size && heap[rightChildIndex] < heap[smallest]) {
smallest = rightChildIndex;
}
// If there is no child with lower value, stop
if (smallest == index) {
break;
}
// Otherwise, swap and update 'index' to continue the loop from the new position
swap(index, smallest);
index = smallest;
}
}
public Integer getMin() {
if (size == 0) return null;
return heap[0];
}
private Integer getParentIndex(Integer childIndex) {
// No parent for the root
if (childIndex == 0) return null;
return (childIndex % 2 == 0) ? (childIndex - 1) / 2 : childIndex / 2;
}
private void swap(int i, int j){
int temp = heap[i];
heap[i] = heap[j];
heap[j] = temp;
}
private Integer getLeftChild(Integer parentIndex) {
return 2 * parentIndex + 1;
}
private Integer getRightChild(Integer parentIndex) {
return 2 * parentIndex + 1;
}
}