sort包提供了排序切片和用户自定义数据集以及相关功能的函数。
sort包主要针对[]int
、[]float64
、[]string
、以及其他自定义切片的排序。
主要包括:
type Interface interface {
Len() int // 获取数据集合元素个数
Less(i, j int) bool // 如果i索引的数据小于j索引的数据,返回true,不会调用下面的Swap(),即数据升序排序。
Swap(i, j int) // 交换i和j索引的两个元素的位置
}
实例演示:
package main
import (
"fmt"
"sort"
)
type NewInts []uint
func (n NewInts) Len() int {
return len(n)
}
func (n NewInts) Less(i, j int) bool {
fmt.Println(i, j, n[i] < n[j], n)
return n[i] < n[j]
}
func (n NewInts) Swap(i, j int) {
n[i], n[j] = n[j], n[i]
}
func main() {
n := []uint{
1, 3, 2}
sort.Sort(NewInts(n))
fmt.Println(n)
}
运行结果:
[Running] go run "c:\Users\Mechrevo\Desktop\go_pro\test.go"
1 0 false [1 3 2]
2 1 true [1 3 2]
1 0 false [1 2 3]
[1 2 3]
[Done] exited with code=0 in 1.105 seconds
func Ints(a []int)
func IntsAreSorted(a []int) bool
func SearchInts(a []int, x int) int
func Float64s(a []float64)
func Float64sAreSorted(a []float64) bool
func SearchFloat64s(a []float64, x float64) int
func SearchFloat64s(a []float64, x float64) bool
func Strings(a []string)
func StringsAreSorted(a []string) bool
func SearchStrings(a []string, x string) int
func Sort(data Interface)
func Stable(data Interface)
func Reverse(data Interface) Interface
func IsSorted(data Interface) bool
func Search(n int, f func(int) bool) int
对数据集合(包括自定义数据类型的集合)排序,需要实现sort.Interface
接口的三个方法,即:
type Interface interface {
Len() int // 获取数据集合元素个数
Less(i, j int) bool // 如果i索引的数据小于j索引的数据,返回true,不会调用下面的Swap(),即数据升序排序。
Swap(i, j int) // 交换i和j索引的两个元素的位置
}
实现了这三个方法后,即可调用该包的Sort()方法进行排序。 Sort()方法定义如下:
func Sort(data Interface)
Sort()方法惟一的参数就是待排序的数据集合。
sort包提供了IsSorted方法,可以判断数据集合是否已经排好顺序。IsSorted方法的内部实现依赖于我们自己实现的Len()和Less()方法:
func IsSorted(data Interface) bool {
n := data.Len()
for i := n - 1; i > 0; i