TODO: 修正 index

This commit is contained in:
eson 2019-02-11 01:27:47 +08:00
parent 3ff7e7e855
commit 841c58b4e8
2 changed files with 50 additions and 14 deletions

View File

@ -23,14 +23,14 @@ type Index struct {
type Node struct {
value interface{}
prev *Node
// prev *Node
next *Node
}
// NewWithInt compare use int
func NewWithInt() *PriorityQueue {
p := new(PriorityQueue)
p.indexlimit = 10
p.indexlimit = 20
p.comparator = func(a, b interface{}) int {
if a.(int) > b.(int) {
return 1
@ -43,19 +43,29 @@ func NewWithInt() *PriorityQueue {
func (pq *PriorityQueue) String() string {
content := ""
for cur := pq.node; cur != nil; cur = cur.next {
var prevcontent string
if cur.prev != nil {
prevcontent = "(" + spew.Sprint(cur.prev.value) + "<-)"
} else {
prevcontent = "(nil)"
}
// var prevcontent string
// if cur.prev != nil {
// prevcontent = "(" + spew.Sprint(cur.prev.value) + "<-)"
// } else {
// prevcontent = "(nil)"
// }
content += spew.Sprint(cur.value) + prevcontent + "-"
// content += spew.Sprint(cur.value) + prevcontent + "-"
content += spew.Sprint(cur.value) + "-"
}
if content[len(content)-1] == '-' {
content = content[:len(content)-1]
if content != "" {
if content[len(content)-1] == '-' {
content = content[:len(content)-1]
}
}
return content
idxContent := ""
for idx := pq.index; idx != nil; idx = idx.next {
idxContent += spew.Sprint(idx.node.value) + "(" + spew.Sprint(idx.nlen) + ")-"
}
return content + "\n" + idxContent
}
func (pq *PriorityQueue) Push(v interface{}) {
@ -69,6 +79,9 @@ func (pq *PriorityQueue) Push(v interface{}) {
index.nlen = 1
index.node = node
pq.index = index
pq.node = node
return
}
// find the node of index to start
@ -95,12 +108,27 @@ func (pq *PriorityQueue) Push(v interface{}) {
node.next = cur
pq.index.node = pq.node
pq.index.nlen++
// cur.prev = node
return
}
for cur.next != nil {
for i := 0; cur.next != nil; i++ {
if i >= pq.indexlimit-1 {
if idx.nlen >= pq.indexlimit*2 {
index := new(Index)
index.node = node
index.nlen = idx.nlen - pq.indexlimit
index.next = idx.next
idx.next = index
idx.nlen = pq.indexlimit
idx = index
i = 0
}
}
if pq.comparator(v, cur.next.value) > 0 {
temp := cur.next
@ -111,16 +139,23 @@ func (pq *PriorityQueue) Push(v interface{}) {
idx.nlen++
// if pq.index.nlen >= pq.indexlimit {
// // 分裂
// }
return
}
cur = cur.next
}
cur.next = node
// node.prev = cur
pq.size++
idx.nlen++
}

View File

@ -37,8 +37,9 @@ func TestNPQ(t *testing.T) {
func TestPriorityQueue(t *testing.T) {
p := NewWithInt()
for i := 0; i < 10; i++ {
for i := 0; i < 20; i++ {
p.Push(randomdata.Number(0, 10000))
t.Log(p.String())
}
t.Error(p.String())