GO常用包学习笔记 sort:排序相关(三)
对数组切片进行排序操作;判断是否已正序排序;使用二分法从切片中查找一个元素(要先正序排序)。
对基本类型的切片排序
[]float64,[]int,[]string的排序(递增),判断可以直接使用以下六个方法
func Float64s(a []float64)
func Ints(a []int)
func Strings(a []string)
func Float64sAreSorted(a []float64) bool
func IntsAreSorted(a []int) bool
func StringsAreSorted(a []string) bool
以上6个方法都是间接通过排序接口"Interface"进行排序的
通过实现Interface接口对自定义类型的数组切片进行排序
需实现接口的三个方法
Len() int//长度
Less(i, j int) bool//比较
Swap(i, j int)//交换
满足接口的集合就可以使用以下四个方法
func Sort(data Interface)//排序不保证相等的元素排序前后的顺序
func IsSorted(data Interface) bool//判断是否正序
func Stable(data Interface)//排序 保证相等的元素排序前后的顺序
func Reverse(data Interface) Interface//(排序前)修改排序接口的比大小方法
基本类型的排序就是通过如下三个实现了Interface接口的对象来实现的
type Float64Slice//type Float64Slice[]float64
func (p Float64Slice) Len() int
func (p Float64Slice) Less(i, j int) bool
func (p Float64Slice) Search(x float64) int
func (p Float64Slice) Sort()
func (p Float64Slice) Swap(i, j int)
type IntSlice
func (p IntSlice) Len() int
func (p IntSlice) Less(i, j int) bool
func (p IntSlice) Search(x int) int
func (p IntSlice) Sort()
func (p IntSlice) Swap(i, j int)
type StringSlice
func (p StringSlice) Len() int
func (p StringSlice) Less(i, j int) bool
func (p StringSlice) Search(x string) int
func (p StringSlice) Sort()
func (p StringSlice) Swap(i, j int)
上面几个Search方法(二分法,要先递增排序才能用)通过下面三个方法实现
func SearchFloat64s(a []float64, x float64) int
func SearchInts(a []int, x int) int
func SearchStrings(a []string, x string) int
而这三个方法调用了Search方法
func Search(n int, f func(int) bool) int//二分法
Go1.8新增的排序方法
func Slice(slice interface{}, less func(i, j int) bool)//排序 不保证相同的元素的次序
func SliceStable(slice interface{}, less func(i, j int) bool)//排序 保证排序后相同的元素的先后顺序不变
func SliceIsSorted(slice interface{}, less func(i, j int) bool) bool//是否为正序排列
入参slice必须是一个数组切片,否则发生panic
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。