标准方法
golang的sort在封装之后还挺好用的,但是封装略微有点繁琐。
首先需要被排序的数组声明一个别名:
type Test struct {
Math int
Chinese int
}
type StuScores []Test
然后需要该类型实现三个方法:
func (s StuScores) Len() int
func (s StuScores) Swap(i, j int)
func (s StuScores) Less(i, j int) bool
实现完毕后就可以使用以下的方法进行排序操作:
sort.Sort(s) //正序
sort.Sort(sort.Reverse(s)) //逆序
此外还能自动实现以下的方法:
sort.IsSorted(s) //返回是否已经有序的bool
给出我一的一个例子:
实现按照chinese排序
type Test struct {
Math int
Chinese int
}
type StuScores []Test
func (s StuScores) Len() int {
return len(s)
}
func (s StuScores) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s StuScores) Less(i, j int) bool {
return s[i].Chinese < s[j].Chinese
}
func main() {
s := StuScores{Test{Math: 12, Chinese: 22}, Test{Math: 42, Chinese: 41}, Test{Math: 532, Chinese: 53}}
for _, v := range s {
fmt.Println(v.Chinese, v.Math)
}
sort.Sort(s)
fmt.Println()
for _, v := range s {
fmt.Println(v.Chinese, v.Math)
}
fmt.Println("is sort ?", sort.IsSorted(s))
sort.Sort(sort.Reverse(s))
for _, v := range s {
fmt.Println(v.Chinese, v.Math)
}
}
快速定义法
使用sort.Silce方法可以快速指定比较函数,类似于C++的结构体排序,emmm、、、感觉这才是正确的打开方式:
下面实现的是按照分数(Score)的降序排序效果:
package main
import (
"fmt"
"sort"
)
type Student struct {
Name string
Score int
ID int
}
func main() {
stuList := make([]Student, 0, 4)
stuList = append(stuList, []Student{
{
ID: 1,
Score: 23,
Name: "Tome",
},
{
ID: 5,
Score: 88,
Name: "Smile",
},
{
ID: 2,
Score: 99,
Name: "FFOl",
},
{
ID: 3,
Score: 33,
Name: "LOP",
},
}...)
sort.Slice(stuList, func(i, j int) bool {
return stuList[i].Score > stuList[j].Score
})
fmt.Println(stuList)
}
输出:
[{FFOl 99 2} {Smile 88 5} {LOP 33 3} {Tome 23 1}]