官方文档Golang的sort包用来排序,二分查找等操作。本文主要介绍sort包里常用的函数,通过实例代码来快速学会使用sort包
ints := []int{1, 4, 3, 2} fmt.Printf("%v\n", ints) sort.Ints(ints) //默认升序 fmt.Printf("%v\n", ints) //[1 2 3 4] sort.Sort(sort.Reverse(sort.IntSlice(ints))) //降序排序 fmt.Printf("%v\n", ints) //[4 3 2 1]
sort.Strings(x []string)
sort.Float64s(x []float64)
slices := []int{1, 1, 4, 5, 1, 4} sort.Slice(slices, func(i, j int) bool { return slices[i] < slices[j] }) fmt.Printf("%v\n", slices)//[1 1 1 4 4 5]
type stu struct { name string age int } stus := []stu{{"h", 20}, {"a", 23}, {"h", 21}} sort.Slice(stus, func(i, j int) bool { if stus[i].name == stus[j].name { return stus[i].age > stus[j].age // 年龄逆序 } return stus[i].name < stus[j].name // 名字正序 }) fmt.Printf("%v\n", stus) //[{a 23} {h 21} {h 20}]
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) }
type stu struct { name string age int } type student []stu func (s student) Len() int { return len(s) } func (s student) Less(i, j int) bool { if s[i].name == s[j].name { return s[i].age > s[j].age // 年龄逆序 } return s[i].name < s[j].name // 名字正序 } func (s student) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func main() { stus1 := student{{"h", 20}, {"a", 23}, {"h", 21}} sort.Sort(stus1) fmt.Printf("%v\n", stus1) //[{a 23} {h 21} {h 20}] 使用效果等同于sort.Slice }
arr := []int{1, 2, 3, 4, 5, 6, 7} idx := sort.SearchInts(arr, 4) fmt.Printf("%v\n", idx) // 3
sort.SearchFloat64s(a []float64, x float64) int
sort.SearchStrings(a []string, x string) int
arr := []int{1, 2, 3, 4, 5, 6, 7} idx := sort.Search(len(arr), func(i int) bool { return arr[i] > 4 }) fmt.Printf("%v\n", idx) //4
mysring := []string{"abcd", "bcde", "bfag", "cddd"} 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]) // cddd mysring := []string{"abcd", "bcde", "bfag", "cddd"} idx := sort.Search(len(mysring), func(i int) bool { //查找第一个字母不是b的 return mysring[i][0] <= byte('b') }) fmt.Printf("%v\n", mysring[idx]) // abcd