本文讲解切片(数组)的排序,为什么是切片,而不是数组,因为数组是定长的,且不能改变长度,而切片是可扩展长度的,而且切片的传值排序会直接改变其本身的顺序
1. 普通排序
1.1 数字切片排序
a := []int{4,5,7,3,2}
sort.Ints(a)
fmt.Println(a)
打印结果:
[2 3 4 5 7]
1.2 其他类型切片排序
类型 | 函数 |
---|---|
int | sort.Ints(a []int) |
int | sort.Float64s(a []float64) |
int | sort.Strings(a []string) |
2. 自定义实现排序
sortSort
func (a Type)Len() int {}
func (a Type)Less(i,j int) bool {}
func (a Type)Swap(i,j int){}
举个栗子:
type Sd struct {
Id int
Score float64
}
type Ssd []Sd
func (sd Ssd)Len() int {
return len(sd)
}
func (sd Ssd)Less(i,j int) bool {
return sd[i].Id < sd[j].Id
}
func (sd Ssd)Swap(i,j int){
sd[i],sd[j] = sd[j],sd[i]
}
func main(){
sd := Ssd{
{2,12.3},
{1,17.3},
{4,15.3},
{3,13.3},
}
sort.Sort(sd)
fmt.Println(sd)
}
打印结果:
[{1 17.3} {2 12.3} {3 13.3} {4 15.3}]
3.二维数组按某列排序
sort.Slice
type Data struct {
Id int
Name string
Score float32
Age int
High float32
}
func sortByColumn(column string,data []Data) {
sort.Slice(data, func(i, j int) bool {
switch column {
case "Id":
return data[i].Id < data[j].Id
case "Name":
return data[i].Name < data[j].Name
case "Score":
return data[i].Score < data[j].Score
case "Age":
return data[i].Age < data[j].Age
case "High":
return data[i].High < data[j].High
default:
return data[i].Id < data[j].Id
}
})
}
func main() {
var data = []Data{
{5,"zhangsan",92,20,1.75},
{3,"lisi",100,22,1.85},
{2,"wangwu",67,19,1.65},
{4,"zhaoliu",88,21,1.71},
{1,"wuqi",90,20,1.70},
}
sortByColumn("Score",data[:])
for _,v := range data {
fmt.Println(v)
}
}
打印结果:
{2 wangwu 67 19 1.65}
{4 zhaoliu 88 21 1.71}
{1 wuqi 90 20 1.7}
{5 zhangsan 92 20 1.75}
{3 lisi 100 22 1.85}
如果有更好的方案,欢迎评论