diff --git a/src/heaps/mutable_binary_heap.jl b/src/heaps/mutable_binary_heap.jl index cc6525de7..abc87d0d6 100644 --- a/src/heaps/mutable_binary_heap.jl +++ b/src/heaps/mutable_binary_heap.jl @@ -1,5 +1,7 @@ # Binary heap +include("arrays_as_heaps.jl") + struct MutableBinaryHeapNode{T} value::T handle::Int @@ -131,10 +133,10 @@ end function _make_mutable_binary_heap(ord::Ordering, ty::Type{T}, values) where T # make a static binary index tree from a list of values - n = length(values) nodes = Vector{MutableBinaryHeapNode{T}}(undef, n) nodemap = Vector{Int}(undef, n) + values = heapify!(values, ord) i::Int = 0 for v in values @@ -143,9 +145,6 @@ function _make_mutable_binary_heap(ord::Ordering, ty::Type{T}, values) where T @inbounds nodemap[i] = i end - for i = 1 : n - _heap_bubble_up!(ord, nodes, nodemap, i) - end return nodes, nodemap end diff --git a/test/test_mutable_binheap.jl b/test/test_mutable_binheap.jl index 9af1d963b..2dbe7ab29 100644 --- a/test/test_mutable_binheap.jl +++ b/test/test_mutable_binheap.jl @@ -52,11 +52,12 @@ end @testset "MutableBinheap" begin - vs = [4, 1, 3, 2, 16, 9, 10, 14, 8, 7] - vs2 = collect(enumerate(vs)) ordering = Base.Order.By(last) @testset "construct heap" begin + vs = [4, 1, 3, 2, 16, 9, 10, 14, 8, 7] + vs2 = collect(enumerate(vs)) + MutableBinaryHeap{Int, Base.ForwardOrdering}() MutableBinaryHeap{Int, Base.ForwardOrdering}(vs) @@ -88,6 +89,7 @@ end end @testset "make mutable binary minheap" begin + vs = [4, 1, 3, 2, 16, 9, 10, 14, 8, 7] h = MutableBinaryMinHeap(vs) @test length(h) == 10 @@ -99,17 +101,20 @@ end end @testset "make mutable binary maxheap" begin + vs = [4, 1, 3, 2, 16, 9, 10, 14, 8, 7] h = MutableBinaryMaxHeap(vs) @test length(h) == 10 @test !isempty(h) @test first(h) == 16 @test isequal(list_values(h), vs) - @test isequal(heap_values(h), [16, 14, 10, 8, 7, 3, 9, 1, 4, 2]) + @test isequal(heap_values(h), [16, 14, 10, 8, 7, 9, 3, 2, 4, 1]) @test sizehint!(h, 100) === h end @testset "make mutable binary custom ordering heap" begin + vs = [4, 1, 3, 2, 16, 9, 10, 14, 8, 7] + vs2 = collect(enumerate(vs)) h = MutableBinaryHeap(ordering, vs2) @test length(h) == 10 @@ -121,6 +126,7 @@ end end @testset "hmin / push! / pop!" begin + vs = [4, 1, 3, 2, 16, 9, 10, 14, 8, 7] hmin = MutableBinaryMinHeap{Int}() @test length(hmin) == 0 @test isempty(hmin) @@ -152,6 +158,7 @@ end end @testset "hmax / push! / pop!" begin + vs = [4, 1, 3, 2, 16, 9, 10, 14, 8, 7] hmax = MutableBinaryMaxHeap{Int}() @test length(hmax) == 0 @test isempty(hmax) @@ -183,6 +190,8 @@ end end @testset "Custom ordering push! / pop!" begin + vs = [4, 1, 3, 2, 16, 9, 10, 14, 8, 7] + vs2 = collect(enumerate(vs)) heap = MutableBinaryHeap{Tuple{Int,Int}}(ordering) @test length(heap) == 0 @test isempty(heap)