From 411281d865d7eaa5586e2e36d418316b9e67ee50 Mon Sep 17 00:00:00 2001 From: huangsimin Date: Thu, 1 Aug 2019 10:07:26 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96heap?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tree/heap/heap.go | 17 ++++++--------- tree/heap/heap_test.go | 49 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 10 deletions(-) diff --git a/tree/heap/heap.go b/tree/heap/heap.go index b574056..b471dc0 100644 --- a/tree/heap/heap.go +++ b/tree/heap/heap.go @@ -110,40 +110,37 @@ func (h *Heap) Pop() (interface{}, bool) { downvalue := h.elements[h.size] var cidx, c1, c2 int - var cvalue1, cvalue2, cvalue interface{} + var cvalue1, cvalue2 interface{} // down for { cidx = curidx << 1 + c1 = cidx + 1 c2 = cidx + 2 - if c2 < h.size { - cvalue2 = h.elements[c2] - c1 = cidx + 1 + if c2 < h.size { + + cvalue2 = h.elements[c2] cvalue1 = h.elements[c1] if h.Compare(cvalue1, cvalue2) >= 0 { cidx = c1 - cvalue = cvalue1 } else { cidx = c2 - cvalue = cvalue2 } } else { - c1 = cidx + 1 if c1 < h.size { cvalue1 = h.elements[c1] cidx = c1 - cvalue = cvalue1 } else { break } } - if h.Compare(cvalue, downvalue) > 0 { - h.elements[curidx] = cvalue + if h.Compare(h.elements[cidx], downvalue) > 0 { + h.elements[curidx] = h.elements[cidx] curidx = cidx } else { break diff --git a/tree/heap/heap_test.go b/tree/heap/heap_test.go index 5d085df..b41f38e 100644 --- a/tree/heap/heap_test.go +++ b/tree/heap/heap_test.go @@ -1,11 +1,60 @@ package heap import ( + "sort" "testing" "github.com/474420502/focus/compare" + "github.com/Pallinder/go-randomdata" ) +func TestHeapGrowSlimming(t *testing.T) { + h := New(compare.Int) + var results []int + for i := 0; i < 100; i++ { + v := randomdata.Number(0, 100) + results = append(results, v) + h.Put(v) + } + sort.Slice(results, func(i, j int) bool { + if results[i] > results[j] { + return true + } + return false + }) + + if h.Size() != 100 || h.Empty() { + t.Error("size != 100") + } + + for i := 0; !h.Empty(); i++ { + v, _ := h.Pop() + if results[i] != v { + t.Error("heap is error") + } + } + + if h.Size() != 0 { + t.Error("size != 0") + } + + h.Put(1) + h.Put(5) + h.Put(2) + + if h.Values()[0] != 5 { + t.Error("top is not equal to 5") + } + + h.Clear() + h.Reborn() + + if !h.Empty() { + t.Error("clear reborn is error") + } + +} + func TestHeapPushTopPop(t *testing.T) { h := New(compare.Int) l := []int{9, 5, 15, 2, 3}