-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinHeap.java
More file actions
executable file
·120 lines (91 loc) · 2.74 KB
/
Copy pathMinHeap.java
File metadata and controls
executable file
·120 lines (91 loc) · 2.74 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package com.codeWithArsalon.NonLinearDS;
public class MinHeap {
private class Node {
private int key;
private String value;
public Node(int key, String value) {
this.key = key;
this.value = value;
}
}
private Node[] nodes = new Node[10];
private int size;
public void insert(int key, String value) {
if (isFull())
throw new IllegalStateException();
nodes[size++] = new Node(key, value);
bubbleUp();
}
public String remove() {
if (isEmpty())
throw new IllegalStateException();
var root = nodes[0].value;
nodes[0] = nodes[--size];
bubbleDown();
return root;
}
private void bubbleDown() {
var index = 0;
while (index <= size && !isValidParent(index)) {
var largerChildIndex = smallerChildIndex(index);
swap(index, largerChildIndex);
index = largerChildIndex;
}
}
public boolean isEmpty() {
return size == 0;
}
private int smallerChildIndex(int index) {
if (!hasLeftChild(index))
return index;
if (!hasRightChild(index))
return leftChildIndex(index);
return (leftChild(index).key < rightChild(index).key) ?
leftChildIndex(index) :
rightChildIndex(index);
}
private boolean hasLeftChild(int index) {
return leftChildIndex(index) <= size;
}
private boolean hasRightChild(int index) {
return rightChildIndex(index) <= size;
}
private boolean isValidParent(int index) {
if (!hasLeftChild(index))
return true;
var isValid = nodes[index].key <= leftChild(index).key;
if (hasRightChild(index))
isValid &= nodes[index].key <= rightChild(index).key;
return isValid;
}
private Node rightChild(int index) {
return nodes[rightChildIndex(index)];
}
private Node leftChild(int index) {
return nodes[leftChildIndex(index)];
}
private int leftChildIndex(int index) {
return index * 2 + 1;
}
private int rightChildIndex(int index) {
return index * 2 + 2;
}
public boolean isFull() {
return size == nodes.length;
}
private void bubbleUp() {
var index = size - 1;
while (index > 0 && nodes[index].key < nodes[parent(index)].key) {
swap(index, parent(index));
index = parent(index);
}
}
private int parent(int index) {
return (index - 1) / 2;
}
private void swap(int first, int second) {
var temp = nodes[first];
nodes[first] = nodes[second];
nodes[second] = temp;
}
}