优化heap

This commit is contained in:
huangsimin 2019-08-01 10:07:26 +08:00
parent 5ef163bca7
commit 411281d865
2 changed files with 56 additions and 10 deletions

View File

@ -110,40 +110,37 @@ func (h *Heap) Pop() (interface{}, bool) {
downvalue := h.elements[h.size] downvalue := h.elements[h.size]
var cidx, c1, c2 int var cidx, c1, c2 int
var cvalue1, cvalue2, cvalue interface{} var cvalue1, cvalue2 interface{}
// down // down
for { for {
cidx = curidx << 1 cidx = curidx << 1
c2 = cidx + 2
if c2 < h.size {
cvalue2 = h.elements[c2]
c1 = cidx + 1 c1 = cidx + 1
c2 = cidx + 2
if c2 < h.size {
cvalue2 = h.elements[c2]
cvalue1 = h.elements[c1] cvalue1 = h.elements[c1]
if h.Compare(cvalue1, cvalue2) >= 0 { if h.Compare(cvalue1, cvalue2) >= 0 {
cidx = c1 cidx = c1
cvalue = cvalue1
} else { } else {
cidx = c2 cidx = c2
cvalue = cvalue2
} }
} else { } else {
c1 = cidx + 1
if c1 < h.size { if c1 < h.size {
cvalue1 = h.elements[c1] cvalue1 = h.elements[c1]
cidx = c1 cidx = c1
cvalue = cvalue1
} else { } else {
break break
} }
} }
if h.Compare(cvalue, downvalue) > 0 { if h.Compare(h.elements[cidx], downvalue) > 0 {
h.elements[curidx] = cvalue h.elements[curidx] = h.elements[cidx]
curidx = cidx curidx = cidx
} else { } else {
break break

View File

@ -1,11 +1,60 @@
package heap package heap
import ( import (
"sort"
"testing" "testing"
"github.com/474420502/focus/compare" "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) { func TestHeapPushTopPop(t *testing.T) {
h := New(compare.Int) h := New(compare.Int)
l := []int{9, 5, 15, 2, 3} l := []int{9, 5, 15, 2, 3}