好的,下面是对Go语言内置sort包内容的详细概括:
1. 排序接口和方法
-
Interface 接口:
Len() int: 返回集合的元素数量。Less(i, j int) bool: 报告索引i的元素是否应排序在索引j的元素之前。Swap(i, j int): 交换索引i和j的元素。
-
排序函数:
Sort(data Interface): 对实现了Interface接口的集合进行排序。排序算法是快速排序,复杂度为O(n*log(n))。不保证稳定性。Stable(data Interface): 稳定排序算法,保留相等元素的原始顺序。复杂度为O(n*log(n)*log(n))。IsSorted(data Interface) bool: 检查集合是否已排序。
2. 反转排序
- Reverse:
Reverse(data Interface) Interface: 返回一个新的Interface实现,该实现按相反顺序排序。reverse结构体:嵌入Interface,并实现Less方法,使排序顺序相反。
3. 常用类型的排序
-
IntSlice (
[]int):Len() int: 返回切片长度。Less(i, j int) bool: 报告索引i的元素是否小于索引j的元素。Swap(i, j int): 交换索引i和j的元素。Sort(): 对IntSlice进行排序。Search(x int) int: 使用二分查找在IntSlice中搜索x的索引。
-
Float64Slice (
[]float64):Len() int: 返回切片长度。Less(i, j int) bool: 报告索引i的元素是否小于索引j的元素。对NaN值进行了特殊处理,NaN值排序在前。Swap(i, j int): 交换索引i和j的元素。Sort(): 对Float64Slice进行排序。Search(x float64) int: 使用二分查找在Float64Slice中搜索x的索引。
-
StringSlice (
[]string):Len() int: 返回切片长度。Less(i, j int) bool: 报告索引i的元素是否小于索引j的元素。Swap(i, j int): 交换索引i和j的元素。Sort(): 对StringSlice进行排序。Search(x string) int: 使用二分查找在StringSlice中搜索x的索引。
4. 便利函数
-
Ints, Float64s, Strings:
Ints(x []int): 对[]int进行排序。Float64s(x []float64): 对[]float64进行排序。Strings(x []string): 对[]string进行排序。
-
IntsAreSorted, Float64sAreSorted, StringsAreSorted:
IntsAreSorted(x []int) bool: 检查[]int是否已排序。Float64sAreSorted(x []float64) bool: 检查[]float64是否已排序。StringsAreSorted(x []string) bool: 检查[]string是否已排序。
5. 二分查找
-
Search:
Search(n int, f func(int) bool) int: 使用二分查找找到第一个满足f(i)为true的索引。
-
SearchInts, SearchFloat64s, SearchStrings:
SearchInts(a []int, x int) int: 在排序的[]int中查找x的索引。SearchFloat64s(a []float64, x float64) int: 在排序的[]float64中查找x的索引。SearchStrings(a []string, x string) int: 在排序的[]string中查找x的索引。
6. 切片排序
- Slice, SliceStable, SliceIsSorted:
Slice(x any, less func(i, j int) bool): 对任意切片x使用比较函数less进行排序。使用反射确保x是一个切片。SliceStable(x any, less func(i, j int) bool): 对任意切片x使用比较函数less进行稳定排序。SliceIsSorted(x any, less func(i, j int) bool) bool: 检查任意切片x是否已按照比较函数less排序。
通过这些接口和函数,sort包提供了对各种数据类型进行排序和查找的灵活工具,适用于各种排序需求。
下面是对结构体排序的示例:(根据Person年龄降序排序)
package main
import (
"log"
"sort"
)
type Person struct {
Name string
Age int
}
func main() {
persons := []Person{
{Name: "1", Age: 18},
{Name: "2", Age: 20},
{Name: "3", Age: 19},
{Name: "4", Age: 30},
{Name: "5", Age: 23},
}
sort.Slice(persons, func(i, j int) bool {
return persons[i].Age > persons[j].Age
})
for _, value := range persons {
log.Println(value.Name, value.Age)
}
}