文章目錄
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