Golang Heapソートアルゴリズム

1218 ワード

Golang containerパッケージのvectorとheapを組み合わせると、heapアルゴリズムのキューを実現できます.Vectorはinterface{}インタフェースを実現し、vectorが実現する限り任意のstruct要素を配置することができる.LessInterfaceはheapでソートできます.次のようになります.
 
type elem struct {
    idx int64
    name string
}
func (p *elem) Less(y interface{}) bool {
    return p.idx < y.(*elem).idx
}

これによりelemの要素はheapアルゴリズムにより,VectorからPushまたはPopを秩序正しく動かすことができる.完全なコードは次のとおりです.
 
package main

import (
    "container/heap"
    "container/vector"
    "fmt"
)

type elem struct {
    idx int64
    name string
}
func (p *elem) Less(y interface{}) bool {
    return p.idx < y.(*elem).idx
}

func test() {
    v := &vector.Vector{}
    heap.Init(v)
    heap.Push(v, &elem{10, "test10"})
    heap.Push(v, &elem{100, "test100"})
    heap.Push(v, &elem{9, "test9"})
    for i:=0; i < 3; i++ {
        fmt.Println(heap.Pop(v).(*elem).name)
    }
}

func main() {
    test()
}