steveyen / gtreap

gtreap is an immutable treap implementation in the Go Language
MIT License
89 stars 22 forks source link

Priority problem #3

Closed icexin closed 9 years ago

icexin commented 9 years ago
type Item struct {
    Key string
    Pri int
}

func itemCompare(a, b interface{}) int {
    return strings.Compare(a.(Item).Key, b.(Item).Key)
}

func main() {
    s := gtreap.NewTreap(itemCompare)
    s = s.Upsert(Item{"m", 20}, 20)
    s = s.Upsert(Item{"l", 18}, 18)
    s = s.Upsert(Item{"n", 19}, 19)
    s = s.Upsert(Item{"m", 4}, 4)
    s.VisitAscend(Item{"", 0}, func(i gtreap.Item) bool {
        item := i.(Item)
        fmt.Printf("%s %d\n", item.Key, item.Pri)
        return true
    })

}

It prints

l 18
m 4
n 19

m as root node with priority 4 is lower than it's sons. The reason is in https://github.com/steveyen/gtreap/blob/master/treap.go#L86 When middle is not nil, use middle's priority as result node's priority Always use this.priority should get the correct answer.

steveyen commented 9 years ago

Thanks! Fixed in commit 0abe01e