go基础之自定义排序

自定义排序需要先定义一个类型,然后需要实现三个接口,Len,Less,Swap这三个,分别是长度,比较,交换。

package main

import (
"fmt"
"sort"
)

type MyStringList []string

func (m MyStringList) Len() int {
return len(m)
}


func (m MyStringList) Less(i, j int) bool {
return m[i] < m[j]
}

func (m MyStringList) Swap(i, j int) {
m[i], m[j] = m[j], m[i]
}

func main() {
names := MyStringList{
"3.abc",
"5.rty",
"4.ade",
"2.vbn",
"1.ppp",

}
sort.Sort(names)
for _, v := range names {
fmt.Println(v)
}

//字符串自带排序
strnames := []string{
"3.abc",
"5.rty",
"4.ade",
"2.vbn",
"1.ppp",
}
sort.Strings(strnames)
for _, v := range strnames {
fmt.Println(v)
}
}

上面sort.Strings(strnames)是字符串排序,标准库已经实现的,sort.Sort(names)是自定义排序,只不过自定义的类型是字符串切片,当然也可以是其他类型。

package main

import (
"fmt"
"sort"
)
type HeroKind int
const (
None HeroKind = iota
Tank
Assassin
Mage
)

type Hero struct {
Name string
Kind HeroKind
}

type Heros []*Hero

func (s Heros) Len() int {
return len(s)
}

func (s Heros) Less(i, j int) bool {
if s[i].Kind != s[j].Kind {
return s[i].Kind < s[j].Kind
}
return s[i].Name < s[j].Name
}

func (s Heros) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}

func main() {
heros := Heros{
&Hero{"张三", Tank},
&Hero{"李四", Assassin},
&Hero{"王五", Mage},
&Hero{"麻六", Assassin},
&Hero{"李四", Tank},
&Hero{"王五", Mage},
}
sort.Sort(heros)
for _, v := range heros {
fmt.Println(v)
}
}
发表评论

相关文章