Go sort包

sort包简介

官方文档
Golang的sort包用来排序,二分查找等操作。本文主要介绍sort包里常用的函数,通过实例代码来快速学会使用sort包

sort包内置函数

sort.Ints(x []int)

    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)

  • 使用方法同上,都是对内置 int string float64类型的便捷排序

sort.Slice(x any, less func(i, j int) bool)

  • 传入对象是切片,要自己实现回调函数
    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}]

sort.Sort(data Interface)

  • 自定义排序,需要实现 Len() Less() Swap() 三个方法
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
}
  • 使用效果等同于 sort.Slice后者代码量较少

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

  • 该函数是用来二分查找的, 默认是在左边插入
    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

  • 这两函数功能同上

sort.Search(n int, f func(int) bool) 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
  • 相比 SearchInts,通过自定义条件便实现了相等情况下在右边插入,前者默认是在左边
  • 更高级一点的用法
    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]

Original: https://www.cnblogs.com/notomatoes/p/16277688.html
Author: Notomato
Title: Go sort包

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

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

(0)

大家都在看

  • Go能实现AOP吗?

    hello~大家好,我是小楼,今天分享的话题是 Go&#x662F;&#x5426;&#x80FD;&#x5B9E;&#x73B0;AOP?…

    Go语言 2023年5月25日
    072
  • RSA.js_公钥加密_NoPadding_golang实现_n_e_pem格式互转

    转载注明来源:本文链接 来自osnosn的博客,写于 2021-09-13. 参考 PKCS1【Golang 实现RSA加密解密】 PKCS1,密钥格式转换(需第三方包)【RSA非…

    Go语言 2023年5月25日
    055
  • Golang接口型函数使用技巧

    什么是接口型函数?顾名思义接口函数指的是用函数实现接口,这样在调用的时候就会非常简便,这种方式适用于只有一个函数的接口。 这里以迭代一个map为例,演示这一实现的技巧。 常规接口实…

    Go语言 2023年5月25日
    052
  • Goland的那些实用技巧

    1、 自定义结构体tag 2、go mod tidy / download失败 解决办法:设置goproxy 3、取消/打开代码折叠 4、左侧project栏总是展示当前打开文件的…

    Go语言 2023年5月25日
    064
  • go语言异常处理

    go语言异常处理 go语言引入了一个关于错误错里的标准模式,即error接口,该接口的定义如下: type error interface{ Error() string } 对于…

    Go语言 2023年5月29日
    057
  • 生产者消费者模型及Golang简单实现

    简介:介绍生产者消费者模型,及go简单实现的demo。 一、生产者消费者模型 生产者消费者模型:某个模块(函数等〉负责产生数据,这些数据由另一个模块来负责处理(此处的模块是广义的,…

    Go语言 2023年5月25日
    043
  • Go单元测试实践

    单元测试通常用来在日常开发中检查代码中存在的问题,是提升代码质量一种有效手段。在保证代码功能没有问题的同时,可以得到预期结果。Golang有许多优秀的框架支持UT,下面列举日常开发…

    Go语言 2023年5月25日
    066
  • 【Docker】使用Docker Client和Docker Go SDK为容器分配GPU资源

    深度学习的环境配置通常是一项比较麻烦的工作,尤其是在多个用户共享的服务器上。虽然conda集成了virtualenv这样的工具用来隔离不同的依赖环境,但这种解决方案仍然没办法统一地…

    Go语言 2023年5月25日
    067
  • Golang通脉之指针

    指针的概念 指针是存储另一个变量的内存地址的变量。 变量是一种使用方便的占位符,用于引用计算机内存地址。 一个指针变量可以指向任何一个值的内存地址。 在上面的图中,变量b的值为15…

    Go语言 2023年5月25日
    052
  • Go语言 context包源码学习

    你必须非常努力,才能看起来毫不费力!微信搜索公众号[ 漫漫Coding路 ],一起From Zero To Hero ! 日常 Go 开发中,Context 包是用的最多的一个了,…

    Go语言 2023年5月25日
    063
  • 盘点Go中的开发神器

    本文已收录 https://github.com/lkxiaolou/lkxiaolou 欢迎star。 在Java中,我们用Junit做单元测试,用JMH做性能基准测试(benc…

    Go语言 2023年5月25日
    073
  • Go语言之高级篇beego框架之model设计构造查询

    一、model设计构造查询 QueryBuilder 提供了一个简便,流畅的 SQL 查询构造器。在不影响代码可读性的前提下用来快速的建立 SQL 语句。 QueryBuilder…

    Go语言 2023年5月29日
    037
  • golang tcp keepalive研究记录(基于websocket)

    服务器和客户端建立tcp连接以后,客户端/服务器如何知道对方是否挂掉了? 这时候TCP协议提出一个办法,当客户端端等待超过一定时间后自动给服务端发送一个空的报文,如果对方回复了这个…

    Go语言 2023年5月25日
    040
  • 从零开始搭建GoLang语言开发环境

    更多干货文章,更多最新文章,欢迎到作者主博客 菜鸟厚非 一、安装 GoLang 1.1 下载 首先访问 https://go.dev/dl/ 下载 GoLang,下载完成后双击安装…

    Go语言 2023年5月25日
    061
  • 基于LSM的Key-Value数据库实现WAL篇

    上篇文章简单的实现了基于LSM数据库的初步版本,在该版本中如数据写入到内存表后但还未持久化到SSTable排序字符串表,此时正好程序崩溃,内存表中暂未持久化的数据将会丢失。 引入W…

    Go语言 2023年5月25日
    052
  • Golang 源码解读 01、深入解析 strings.Builder、strings.Join

    本文从我的《The Go Programming Language》学习笔记中分离出,单独成一篇文章方便查阅参考。 strings.Builder 源码解析 存在意义 使用 (st…

    Go语言 2023年5月25日
    073
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球