Golang中字符串、数组、切片排序

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

使用接口排序:

sort.Sort(data Interface)

  • 自定义排序,需要实现 Len() Less() Swap() 三个方法

go;gutter:true; type Interface interface { // Len is the number of elements in the collection.</p> <pre><code>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) </code></pre> <p>}</p> <pre><code> 完整代码如下: 上面可以看到,使用效果等同于sort.Slice,只是后者代码量较少。 ## .SearchInts(a []int, x int) int * 该函数是用来二分查找的, 默认是在左边插入 ;gutter:true;
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) int sort.SearchStrings(a []string, x string) int

  • 这两函数功能同上

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

  • 自定义的二分查找,回调函数需要自己实现查找条件

go;gutter:true; package main</p> <p>import ( "fmt" "sort" )</p> <p>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 }</p> <pre><code> - 相比 ,通过自定义条件便实现了相等情况下在右边插入,前者默认是在左边 - 更高级一点的用法 ;gutter:true;
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
}

以上就介绍这么多了。感兴趣的朋友欢迎留言补充哈。

Original: https://www.cnblogs.com/phpper/p/16296020.html
Author: 周伯通之草堂
Title: Golang中字符串、数组、切片排序

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/578383/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球