使用Golang的sort包用来排序,包括二分查找等操作。下面通过实例代码来分享下sort包的使用技巧:

使用接口排序:

sort.Sort(data Interface)
type Interface interface {
    // Len is the number of elements in the collection.
    Len() int
    // Less reports whether the element with
    // 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)
}

 完整代码如下:

上面可以看到,使用效果等同于sort.Slice,只是后者代码量较少。

sort.SearchInts(a []int, x int) int
package main

import (
    "fmt"
    "sort"
)

func main() {
    arr := []int{11, 22, 33, 44, 55, 66, 77}
    idx := sort.SearchInts(arr, 44) // 查找44所在的索引位置,默认0开始
    fmt.Printf("%v\n", idx) // 3
}
sort.SearchFloat64s(a []float64, x float64) intsort.SearchStrings(a []string, x string) int
  • 这两函数功能同上

sort.Search(n int, f func(int) bool) int
package main

import (
    "fmt"
    "sort"
)

func main() {
    arr := []int{11, 22, 33, 44, 55, 66, 77}
    idx := sort.Search(len(arr), func(i int) bool {
        return arr[i] > 44 //查找 >44的值得索引位置即第一个满足条件的55所在的索引
    })
    fmt.Printf("%v\n", idx) //55 索引位置为4
}
package main

import (
    "fmt"
    "sort"
)

func main() {
    mysring := []string{"abcd", "bcde", "cdef", "dbac"}
    idx := sort.Search(len(mysring), func(i int) bool {
        // 查找头两位字母不是b的,,返回找到的第一个
        return mysring[i][0] != 'b' && mysring[i][1] != 'b'
    })
    fmt.Printf("%v\n", mysring[idx]) // cdef
}