sort包提供了对集合排序和查找的基础函数集,主要有两部分:sort和search
一、sort
1. sort对外提供了对集合排序的方法,排序算法的实现是快速排序、堆排序和插入排序的组合,最简单常见的方法是:
func Ints(a []int) //对[]int排序,快排、堆排序和插入排序组合使用,不稳定
func Float64s(a []float64)
func Strings(a []string)
func IntsAreSorted(a []int) bool //判断[]int是否升序有序
func Float64sAreSorted(a []float64) bool
func StringsAreSorted(a []string) bool
|
2.进阶一点的是自定义比较函数的排序,有稳定和不稳定两种,较为通用:
func Slice(slice interface {}, less func (i, j int) bool) //第一个参数必须为Slice, less函数需要在slice[i]<slice[j]时返回true,不稳定
func SliceStable(slice interface {}, less func (i, j int) bool) //同上,稳定
|
3.最为通用的是:
func Sort(data Interface) //对data排序,不稳定, O(n*log(n))比较和O(n*log(n))次交换
func Stable(data Interface) //对data排序,稳定,O(n*log(n))比较和O(n*log(n)*log(n))次交换
// 其中data需要实现以下接口
type Interface interface {
// Len is the number of elements in the collection.
Len() int
// index i should sort before the element with index j.
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
}
|
二、search
1. search对外提供了二分查找的方法,最简单常见的方法是:
func SearchInts(a []int, x int) int //在a中查找x, a必须为升序有序,返回值i满足(i < len(data) && a[i] == x)表示找到,否则没找到
func SearchFloat64s(a []float64, x float64) int
func SearchStrings(a []string, x string) int
|
2.通用的查找,需要自定义比较函数:
func Search(n int, f func (int) bool) int // n是要查找的集合长度,函数f返回true时,二分向左侧进行;返回false时,二分向右侧进行
// example
func t_search() {
ints := []int{ 1 , 4 , 6 , 8 , 9 }
target := 5
i := sort.Search(len(ints), func (i int) bool { // 存在时返回第一次出现的index,不存在时返回要插入的位置,比如查找4返回1,查找5返回2,查找9返回4,查找11返回5
return ints[i] >= target //如果是降序序列,条件为:ints[i] <= target
})
if i < len(ints) && ints[i] == target {
fmt.Println( "found, index:" , i)
} else {
fmt.Println( "not found" )
}
}
|
3.Search的源码
func Search(n int, f func (int) bool) int {
// Define f(-1) == false and f(n) == true.
// Invariant: f(i-1) == false, f(j) == true.
i, j := 0 , n
for i < j {
h := int(uint(i+j) >> 1 ) // avoid overflow when computing h
// i ≤ h < j
if !f(h) {
i = h + 1 // preserves f(i-1) == false
} else {
j = h // preserves f(j) == true
}
}
// i == j, f(i-1) == false, and f(j) (= f(i)) == true => answer is i.
return i
}
|