Skip to content

Commit 46cba0c

Browse files
committed
Early termination of heapUp and heapDown
1 parent db2dde9 commit 46cba0c

File tree

1 file changed

+31
-21
lines changed

1 file changed

+31
-21
lines changed

src/com/jwetherell/algorithms/data_structures/BinaryHeap.java

+31-21
Original file line numberDiff line numberDiff line change
@@ -128,26 +128,6 @@ public boolean add(T value) {
128128
return true;
129129
}
130130

131-
protected void heapUp(int idx) {
132-
int nodeIndex = idx;
133-
T value = this.array[nodeIndex];
134-
while (nodeIndex >= 0) {
135-
int parentIndex = getParentIndex(nodeIndex);
136-
if (parentIndex < 0) break;
137-
T parent = this.array[parentIndex];
138-
139-
if ((type == Type.MIN && parent != null && value.compareTo(parent) < 0)
140-
|| (type == Type.MAX && parent != null && value.compareTo(parent) > 0)
141-
) {
142-
// Node is greater/lesser than parent, switch node with parent
143-
this.array[parentIndex] = value;
144-
this.array[nodeIndex] = parent;
145-
} else {
146-
nodeIndex = parentIndex;
147-
}
148-
}
149-
}
150-
151131
/**
152132
* {@inheritDoc}
153133
*/
@@ -177,8 +157,37 @@ private T remove(int index) {
177157
return t;
178158
}
179159

160+
protected void heapUp(int idx) {
161+
int nodeIndex = idx;
162+
T value = this.array[nodeIndex];
163+
if (value==null)
164+
return;
165+
166+
while (nodeIndex >= 0) {
167+
int parentIndex = getParentIndex(nodeIndex);
168+
if (parentIndex < 0)
169+
return;
170+
171+
T parent = this.array[parentIndex];
172+
173+
if ((type == Type.MIN && value.compareTo(parent) < 0)
174+
|| (type == Type.MAX && value.compareTo(parent) > 0)
175+
) {
176+
// Node is greater/lesser than parent, switch node with parent
177+
this.array[parentIndex] = value;
178+
this.array[nodeIndex] = parent;
179+
} else {
180+
return;
181+
}
182+
nodeIndex = parentIndex;
183+
}
184+
}
185+
180186
protected void heapDown(int index) {
181187
T value = this.array[index];
188+
if (value==null)
189+
return;
190+
182191
int leftIndex = getLeftIndex(index);
183192
int rightIndex = getRightIndex(index);
184193
T left = (leftIndex != Integer.MIN_VALUE && leftIndex < this.size) ? this.array[leftIndex] : null;
@@ -225,7 +234,8 @@ protected void heapDown(int index) {
225234
nodeToMoveIndex = leftIndex;
226235
}
227236
// No node to move, stop recursion
228-
if (nodeToMove == null) return;
237+
if (nodeToMove == null)
238+
return;
229239

230240
// Re-factor heap sub-tree
231241
this.array[nodeToMoveIndex] = value;

0 commit comments

Comments
 (0)