Skip to content
This repository was archived by the owner on Jan 15, 2021. It is now read-only.

Commit 4d63cd4

Browse files
author
Andreas Anderberg
committed
Fixed problem with BinaryHeap::remove()
When last element was swapped with the removed element it was only propagated downwards. Depending if the swapped value is greater or smaller than its parent it may instead need to propagate upwards. Fixes #108 Change-Id: I9583a3412ccb88166d4e3091ed31a4c8a3aa4486
1 parent d8b533f commit 4d63cd4

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

core-util/BinaryHeap.h

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -193,8 +193,11 @@ class BinaryHeap {
193193
return false;
194194
_swap(i, --_elements); // element i will be destroyed by 'pop_back()' below
195195
_array.pop_back();
196-
if (_elements > 1)
197-
_propagate_down(i);
196+
if ((_elements > 1) && (_elements != i)) {
197+
if (!_propagate_up(i)) {
198+
_propagate_down(i);
199+
}
200+
}
198201
return true;
199202
}
200203
}
@@ -233,20 +236,26 @@ class BinaryHeap {
233236
return (i - 1) / 2;
234237
}
235238

236-
void _propagate_up(size_t node) {
239+
bool _propagate_up(size_t node) {
237240
// This is called when a node is added in the last position in the heap
238241
// We might need to move the node up towards the parent until the heap property
239242
// is satisfied
240243
size_t parent = _parent(node);
244+
bool moved = false;
241245
// Move the node up until it satisfies the heap property
242246
while ((node > 0) && _comparator(_array[node], _array[parent])) {
243247
_swap(node, parent);
244248
node = parent;
245249
parent = _parent(node);
250+
if (node != parent) {
251+
moved = true;
252+
}
246253
}
254+
return moved;
247255
}
248256

249-
void _propagate_down(size_t node) {
257+
bool _propagate_down(size_t node) {
258+
bool moved = false;
250259
// This is called when an existing node is removed
251260
// When that happens, it is replaced with the node at the last position in the heap
252261
// Since that might make the heap inconsistent, we need to move the node down if its
@@ -268,8 +277,12 @@ class BinaryHeap {
268277
break;
269278
}
270279
_swap(node, temp);
280+
if (node != temp) {
281+
moved = true;
282+
}
271283
node = temp;
272284
}
285+
return moved;
273286
}
274287

275288
void _swap(size_t pos1, size_t pos2) {

0 commit comments

Comments
 (0)