自定义slice排序
LenSwapLesssort.Sortsort.Reversesort.Sort(sort.Reverse(IntSlice))
type Person struct {
name string
age int
}
type plist []Person
func (p plist) Len() int {
return len(p)
}
func (p plist) Less(i, j int) bool {
return p[i].age < p[j].age
}
func (p plist) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}
自定义堆排序
PushPopreflect.SliceHeaderLencap
package main
import(
"fmt"
"container/heap"
)
type Person struct {
name string
age int
}
type plist []Person
func (p plist) Len() int {
return len(p)
}
func (p plist) Less(i, j int) bool {
return p[i].age < p[j].age
}
func (p plist) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}
func (p *plist) Push(x interface{}) {
t, ok := x.(Person)
if ok != true {
return
}
*p = append(*p, t)
}
func (p *plist) Pop() interface{} {
l := len(*p)
if l == 0 {
return nil
}
x := (*p)[l-1]
*p = (*p)[:l-1]
return x
}
func main(){
p := []Person{}
p = append(p, Person{"tyl", 21})
p = append(p, Person{"ddd", 212})
p = append(p, Person{"www", 22})
pl := plist(p)
heap.Init(&pl)
for len(pl) > 0 {
fmt.Println(heap.Pop(&pl))
}
}