引言
排序算法一直是很经常使用的功能。Go 语言标准库为我们提供了方便快捷的 sort 包 ,这个包实现了四种基本排序算法:插入排序、归并排序、堆排序和快速排序。
Go 的 sort 包实现了内置和用户定义类型的排序。我们将首先查看内置函数的排序。
常见数据类型排序
为了方便对常用数据类型的操作,sort 包提供了对 []int 切片、[]float64 切片和 []string 切片完整支持:
来看一个简单例子:
package main
import ( "fmt" "sort")
func main() {
s := []int{2022, 2008, 2012, 2025} sort.Ints(s) fmt.Println("Sorted Ints: ", s)
f := []float64{3.14159, 2.14, 19.99} sort.Float64s(f) fmt.Println("Sorted Floats: ", f)
strings := []string{"Kyrie", "Marry", "Allen", "Suzan"} sort.Strings(strings) fmt.Println("Sorted Strings: ", strings)
}
复制代码
运行该代码:
$ go run main.goSorted Ints: [2008 2012 2022 2025]Sorted Floats: [2.14 3.14159 19.99]Sorted Strings: [Allen Kyrie Marry Suzan]
复制代码
sort 提供的几个常见函数:
请注意,排序是就地的,因此它会更改给定的切片并且不会返回新切片。
如果我们想要创建新的,排序的切片,我们使用内置的 make 和 copy 函数。如下所示:
package main
import ( "fmt" "sort")
func main() {
s := []int{2022, 2008, 2012, 2025} // sort.Ints(s) fmt.Println("unSorted Ints: ", s)
sortedInt := make([]int, len(s)) copy(sortedInt, s) sort.Ints(sortedInt) fmt.Println("Sorted Ints: ", sortedInt)
}
复制代码
运行该代码:
$ go run main.gounSorted Ints: [2022 2008 2012 2025]Sorted Ints: [2008 2012 2022 2025]
复制代码
我们还可以使用 sort.IntsAreSorted 来检查 int 切片是否已经排序:
package main
import ( "fmt" "sort")
func main() {
s := []int{2022, 2008, 2012, 2025} // sort.Ints(s) fmt.Println("unSorted Ints: ", s)
sortedInt := make([]int, len(s)) copy(sortedInt, s) sort.Ints(sortedInt) fmt.Println("Sorted Ints: ", sortedInt)
if sort.IntsAreSorted(sortedInt) { fmt.Println("s 已排序") } else { fmt.Println("s 未排序") }
}
复制代码
运行我们的程序:
$ go run main.gounSorted Ints: [2022 2008 2012 2025]Sorted Ints: [2008 2012 2022 2025]s 已排序
复制代码
使用自定义比较器排序
family := []struct { Name string Age int}{ {"Alice", 23}, {"David", 2}, {"Eve", 2}, {"Bob", 25},}
// Sort by age, keeping original order or equal elements.sort.SliceStable(family, func(i, j int) bool { return family[i].Age < family[j].Age})fmt.Println(family) // [{David 2} {Eve 2} {Alice 23} {Bob 25}]
复制代码
对自定义数据结构进行排序
如果对自定义的数据结构做排序排序,那么必须实现 sort.Interface 接口,提供 Len()、Less()、Swap() 三个方法的实现。然后使用通用的 sort.Sort 和 sort.Stable 函数,他们会对任何实现了 sort.Interface 接口的集合进行排序。
以下是 Interface 的具体定义如下:
type Interface interface { // Len is the number of elements in the collection. Len() int // Less reports whether the element with // index i should sort before the element with index j. Less(i, j int) bool // Swap swaps the elements with indexes i and j. Swap(i, j int)}
复制代码
来看这个例子:
type Person struct { Name string Age int}
// ByAge implements sort.Interface based on the Age field.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{ {"Alice", 23}, {"Eve", 2}, {"Bob", 25}, } sort.Sort(ByAge(family)) fmt.Println(family) // [{Eve 2} {Alice 23} {Bob 25}]}
复制代码
按键或值对地图进行排序
映射是键值对的无序集合。如果需要稳定的迭代顺序,则必须维护单独的数据结构。
以下代码示例使用一个键切片按键顺序对映射进行排序。
m := map[string]int{"Alice": 2, "Cecil": 1, "Bob": 3}
keys := make([]string, 0, len(m))for k := range m { keys = append(keys, k)}sort.Strings(keys)
for _, k := range keys { fmt.Println(k, m[k])}// Output:// Alice 2// Bob 3// Cecil 1
复制代码
总结
从本文中,我们了解了排序在 go 语言中的运用,学习了 go 语言 sort 提供的几个方法,并通过实现 sort.Interface 接口对自定义数据结构进行比较。当然,sort 的用法远远不止这些,比如降序、稳定排序。其他的留给大家自己去探索吧。
评论