文章目录
1、接口说明
当一个类要去实现sort排序的时候,只需要实现给出的三个接口方法,然后再调用
func Sort(data Interface)
函数,对传入的数据进行排序即可
type Interface interface {
// Len is the number of elements in the collection.
// 获取数据集合元素个数
Len() int
// 如果 i 索引的数据小于 j 索引的数据,返回 true,且不会调用下面的 Swap(),即数据升序排序
// Less reports whether the element with
// index i should sort before the element with index j.
Less(i, j int) bool
// 交换 i 和 j 索引的两个元素的位置
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
}
2、方法说明
1、Sort - 排序
// Sort sorts data.
// It makes one call to data.Len to determine n, and O(n*log(n)) calls to
// data.Less and data.Swap. The sort is not guaranteed to be stable.
func Sort(data Interface)
2、Reverse - 逆序
逆序排序的实现其实就是修改正序排序的前后入参,也就是说正序是less(i,j),则逆序是less(j,i)
// Reverse returns the reverse order for data.
func Reverse(data Interface) Interface
3、IsSorted - 返回是否排序
// IsSorted reports whether data is sorted.
func IsSorted(data Interface) bool
3、内置结构实现
1、IntSlice
提供方法:
1、Ints - 对[]int 切片排序
// Ints sorts a slice of ints in increasing order.
func Ints(a []int) { Sort(IntSlice(a)) }
2、Search- 在切片中查找对应的int元素
// Search returns the result of applying SearchStrings to the receiver and x.
func (p StringSlice) Search(x string) int
2、Float64Slice
类似同上
3、StringSlice
类似同上
4、函数增强
1、sort.Slice - 自定义排序规则
通过实现匿名函数来实现相应切片的排序规则
// Slice sorts the provided slice given the provided less function.
//
// The sort is not guaranteed to be stable. For a stable sort, use
// SliceStable.
//
// The function panics if the provided interface is not a slice.
func Slice(slice interface{}, less func(i, j int) bool)
2、sort.SliceStable - 稳定排序
// SliceStable sorts the provided slice given the provided less
// function while keeping the original order of equal elements.
//
// The function panics if the provided interface is not a slice.
func SliceStable(slice interface{}, less func(i, j int) bool)
3、sort.SliceIsSorted - 自定义规则判断是否有序
// SliceIsSorted tests whether a slice is sorted.
//
// The function panics if the provided interface is not a slice.
func SliceIsSorted(slice interface{}, less func(i, j int) bool) bool
4、sort.Search - 自定义规则查找
func Search(n int, f func(int) bool) int