package main
import (
"fmt"
"sort"
)
//学生成绩结构体
type StuScore struct {
//姓名
name string
//成绩
score int
}
type StuScores []StuScore
//Len()
func (s StuScores) Len() int {
return len(s)
}
//Less():成绩将有低到高排序
func (s StuScores) Less(i, j int) bool {
return s[i].score < s[j].score
}
//Swap()
func (s StuScores) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func main() {
stus := StuScores{
{"alan", 95},
{"hikerell", 91},
{"acmfly", 96},
{"leao", 90}}
fmt.Println("Default:")
//原始顺序
for _, v := range stus {
fmt.Println(v.name, ":", v.score)
}
fmt.Println()
//StuScores已经实现了sort.Interface接口
sort.Sort(stus)
fmt.Println("Sorted:")
//排好序后的结构
for _, v := range stus {
fmt.Println(v.name, ":", v.score)
}
//判断是否已经排好顺序,将会打印true
fmt.Println("IS Sorted?", sort.IsSorted(stus))
}
golang 关于sort排序的使用
最新推荐文章于 2024-07-30 21:23:52 发布
本文介绍了一个使用Go语言实现的学生分数排序程序。通过定义结构体和sort.Interface接口的方法,实现了对学生分数从低到高的排序,并展示了排序前后的结果对比。
824

被折叠的 条评论
为什么被折叠?



