Skip to content

Commit 40d54aa

Browse files
committed
Fix #678
Added test where a 3-element MutableBinaryMinHeap is created and last element is deleted. This test failed as reported in #678. This test failure was fixed by not swapping and bubbling when the last element in a heap is deleted.
1 parent 1bdd474 commit 40d54aa

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

src/heaps/mutable_binary_heap.jl

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -108,11 +108,12 @@ function _binary_heap_pop!(ord::Ordering,
108108
v = rt.value
109109
@inbounds nodemap[rt.handle] = 0
110110

111-
if length(nodes) == 1
112-
# clear
113-
empty!(nodes)
111+
# if node-to-remove is at end, we can just pop it
112+
# the same applies to 1-element heaps that are empty after removing the last element
113+
if nd_id == lastindex(nodes)
114+
pop!(nodes)
114115
else
115-
# move the last node to the position of the removed node
116+
# otherwise we need to swap the node-to-remove with the last node
116117
@inbounds nodes[nd_id] = new_rt = nodes[end]
117118
pop!(nodes)
118119
@inbounds nodemap[new_rt.handle] = nd_id

test/test_mutable_binheap.jl

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,15 @@ end
266266
@test isequal(heap_values(h), [1])
267267
end
268268

269+
@testset "test delete! at end of 3-element heap" begin
270+
h = MutableBinaryMinHeap{Int}()
271+
push!(h, 1)
272+
push!(h, 2)
273+
handle = push!(h, 3)
274+
delete!(h, handle)
275+
@test isequal(heap_values(h), [1, 2])
276+
end
277+
269278
@testset "test update! and top_with_handle" begin
270279
for (hf,m) = [(MutableBinaryMinHeap,-2.0), (MutableBinaryMaxHeap,2.0)]
271280
xs = rand(100)

0 commit comments

Comments
 (0)