Golang 使用sort包进行排序
Golang的标准库提供了一个包,如果我们想对数组、切片、甚至是自定义类型进行排序,可以使用这个包。在这篇文章中,我们将发现三个主要的函数,如果我们想在Golang中对切片进行排序,我们可以使用它们。我们还将看到如何创建一个自定义排序函数和自定义比较器。
让我们先看看如何对整数、浮点64和字符串的片断进行排序。
例子
考虑一下下面的代码。
package main
import (
"fmt"
"sort"
)
func main() {
integerSlice := []int{3, 2, 14, 9, 11}
sort.Ints(integerSlice)
fmt.Println("After sorting", integerSlice)
floatSlice := []float64{2.32, 9.87, 1.98, 0.88}
sort.Float64s(floatSlice)
fmt.Println("After sorting", floatSlice)
stringSlice := []string{"mukul", "shreya", "naman"}
sort.Strings(stringSlice)
fmt.Println(stringSlice)
}
在上述代码中,我们使用了 sort 包中的以下三个函数
- sort.Ints
-
sort.Float64s
-
sort. Strings
输出
如果我们在上面的代码中运行 go run main.go 命令,那么我们将在终端得到以下输出。
After sorting [2 3 9 11 14]
After sorting [0.88 1.98 2.32 9.87]
[mukul naman shreya]
使用自定义比较器进行排序
例子
如果我们想在 Go 中对一个 结构 进行排序,我们也可以定义一个自定义比较器 。 请看下面的代码。
package main
import (
"fmt"
"sort"
)
type Person struct {
name string
age int
}
func main() {
people := []Person{{"Mukul", 24}, {"Deepak", 26}, {"Mayank", 24}}
fmt.Println("Before sorting", people)
// sorting on the basis of age
sort.Slice(people, func(i, j int) bool {
return people[i].age < people[j].age
})
fmt.Println("After sorting1", people)
// sorting on the basis of name
sort.Slice(people, func(i, j int) bool {
return people[i].name < people[j].name
})
fmt.Println("After sorting2", people)
}
输出
如果我们在上述代码上运行命令 go run main.go ,那么我们将在终端得到以下输出。
Before sorting [{Mukul 24} {Deepak 26} {Mayank 24}]
After sorting1 [{Mukul 24} {Mayank 24} {Deepak 26}]
After sorting2 [{Deepak 26} {Mayank 24} {Mukul 24}]