Go 语言排序

1. 基本使用

使用sort里面的函数我们可以对基本的数据类型进行排序,比如int, float, string
sort.Floats(), sort.Strings...

1
2
s := []int{3,2,4}
sort.Ints(s)

2.使用自定义的比较器

使用sort.Slice(arrs, func(i, j int)bool) 可以对我们的arrs使用func函数进行排序。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package main

import (
"fmt"
"sort"
)

func main() {
stu := []struct {
Name string
grade int
}{
{"Alice", 23},
{"David", 2},
{"Eve", 2},
{"Bob", 25},
}

// 用 age 排序,年龄相等的元素保持原始顺序
sort.SliceStable(stu, func(i, j int) bool {
return stu[i].grade < stu[j].grade
})
fmt.Println(stu) // [{David 2} {Eve 2} {Alice 23} {Bob 25}]
}

3. 排序任意的数据结构

对于数据结构的排序,必须要去实现sort.Interface 接口

1
2
3
4
5
type Interface interface {
Len() int // 数据的长度
Less(i, j int) bool // i, j 是元素的索引
Swap(i, j int) //
}

例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
type Person struct {
Name string
Age int
}
// ByAge 通过对age排序实现了sort.Interface接口
type ByAge []Person
func (a ByAge) Len() int { return len(a) }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] }

func main() {
family := []Person{
{"David", 2},
{"Alice", 23},
{"Eve", 2},
{"Bob", 25},
}
sort.Sort(ByAge(family))
fmt.Println(family) // [{David, 2} {Eve 2} {Alice 23} {Bob 25}]

sort.
}

同时可以根据多个字段进行排序

1