From f63759645ec002b8d1363a0f94720123abd2c9b9 Mon Sep 17 00:00:00 2001 From: huangsimin Date: Thu, 1 Aug 2019 11:21:17 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0heap=E5=8D=95=E5=85=83?= =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tree/heap/heap.go | 5 +---- tree/heap/heap_test.go | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/tree/heap/heap.go b/tree/heap/heap.go index df876aa..126fb08 100644 --- a/tree/heap/heap.go +++ b/tree/heap/heap.go @@ -130,12 +130,9 @@ func (h *Heap) Pop() (interface{}, bool) { } } else { cidx = c1 - if c1 < h.size { - cvalue1 = h.elements[c1] - } else { + if c1 >= h.size { break } - } if h.Compare(h.elements[cidx], downvalue) > 0 { diff --git a/tree/heap/heap_test.go b/tree/heap/heap_test.go index b41f38e..b4c90f8 100644 --- a/tree/heap/heap_test.go +++ b/tree/heap/heap_test.go @@ -80,6 +80,28 @@ func TestHeapPushTopPop(t *testing.T) { if h.Size() != 0 { t.Error("heap size is not equals to zero") } + + h.Clear() + + l = []int{3, 5, 2, 7, 1} + + for _, v := range l { + h.Put(v) + } + + sort.Slice(l, func(i, j int) bool { + if l[i] > l[j] { + return true + } + return false + }) + + for i := 0; !h.Empty(); i++ { + v, _ := h.Pop() + if l[i] != v { + t.Error("heap is error") + } + } } // func Int(k1, k2 interface{}) int {