排序 默认升序
func Ints(x [][int](<https://pkg.go.dev/builtin#int>))
func Float64s(x [][float64](<https://pkg.go.dev/builtin#float64>))
func Strings(x [][string](<https://pkg.go.dev/builtin#string>))
func Slice(x [any](<https://pkg.go.dev/builtin#any>), less func(i, j [int](<https://pkg.go.dev/builtin#int>)) [bool](<https://pkg.go.dev/builtin#bool>))
判断是否有序
func IntsAreSorted(x [][int](<https://pkg.go.dev/builtin#int>)) [bool](<https://pkg.go.dev/builtin#bool>)
func Float64sAreSorted(x [][float64](<https://pkg.go.dev/builtin#float64>)) [bool](<https://pkg.go.dev/builtin#bool>)
func StringsAreSorted(x [][string](<https://pkg.go.dev/builtin#string>)) [bool](<https://pkg.go.dev/builtin#bool>)
func IsSorted(data [Interface](<https://pkg.go.dev/sort#Interface>)) [bool](<https://pkg.go.dev/builtin#bool>)
func SliceIsSorted(x [any](<https://pkg.go.dev/builtin#any>), less func(i, j [int](<https://pkg.go.dev/builtin#int>)) [bool](<https://pkg.go.dev/builtin#bool>)) [bool](<https://pkg.go.dev/builtin#bool>)
查找
func Search(n [int](<https://pkg.go.dev/builtin#int>), f func([int](<https://pkg.go.dev/builtin#int>)) [bool](<https://pkg.go.dev/builtin#bool>)) [int](<https://pkg.go.dev/builtin#int>)
func SearchFloat64s(a [][float64](<https://pkg.go.dev/builtin#float64>), x [float64](<https://pkg.go.dev/builtin#float64>)) [int](<https://pkg.go.dev/builtin#int>)
func SearchInts(a [][int](<https://pkg.go.dev/builtin#int>), x [int](<https://pkg.go.dev/builtin#int>)) [int](<https://pkg.go.dev/builtin#int>)
func SearchStrings(a [][string](<https://pkg.go.dev/builtin#string>), x [string](<https://pkg.go.dev/builtin#string>)) [int](<https://pkg.go.dev/builtin#int>)
通用排序
func Sort(data [Interface](<https://pkg.go.dev/sort#Interface>))
sort.Sort 是一个更通用的排序方法,用于对任何类型的切片进行排序,只要该类型实现了 sort.Interface 接口。sort.Interface 接口包括三个方法:
假设我们有一个结构体 Person,我们希望按年龄对其进行排序。
type Person struct {
Name string
Age int
}
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() {
people := []Person{
{"Alice", 30},
{"Bob", 25},
{"Charlie", 35},
}
sort.Sort(ByAge(people))
fmt.Println(people) // 输出: [{Bob 25} {Alice 30} {Charlie 35}]
}