侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

go语言中sort包的实现方法与应用详解

Go  /  管理员 发布于 5年前   379

前言

Go语言的 sort 包实现了内置和用户定义类型的排序,sort包中实现了3种基本的排序算法:插入排序.快排和堆排序.和其他语言中一样,这三种方式都是不公开的,他们只在sort包内部使用.所以用户在使用sort包进行排序时无需考虑使用那种排序方式,sort.Interface定义的三个方法:获取数据集合长度的Len()方法、比较两个元素大小的Less()方法和交换两个元素位置的Swap()方法,就可以顺利对数据集合进行排序。sort包会根据实际数据自动选择高效的排序算法。

之前跟大家分享了Go语言使用sort包对任意类型元素的集合进行排序的方法,感兴趣的朋友们可以参考这篇文章:///article/60893.htm

下面来看看sort包的简单示例:

type Interface interface { // 返回要排序的数据长度 Len() int //比较下标为i和j对应的数据大小,可自己控制升序和降序  Less(i, j int) bool // 交换下标为i,j对应的数据 Swap(i, j int)}

任何实现了 sort.Interface 的类型(一般为集合),均可使用该包中的方法进行排序。这些方法要求集合内列出元素的索引为整数。

这里我直接用源码来讲解实现:

1、源码中的例子:

type Person struct { Name string Age int}type ByAge []Person//实现了sort接口中的三个方法,则可以使用排序方法了func (a ByAge) Len() int   { return len(a) }func (a ByAge) Swap(i, j int)  { a[i], a[j] = a[j], a[i] }func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }func Example() { people := []Person{  {"Bob", 31},  {"John", 42},  {"Michael", 17},  {"Jenny", 26}, } fmt.Println(people) sort.Sort(ByAge(people)) //此处调用了sort包中的Sort()方法,我们看一下这个方法 fmt.Println(people) // Output: // [Bob: 31 John: 42 Michael: 17 Jenny: 26] // [Michael: 17 Jenny: 26 Bob: 31 John: 42]}

2、Sort(data Interface)方法

//sort包只提供了这一个公开的公使用的排序方法,func Sort(data Interface) { // Switch to heapsort if depth of 2*ceil(lg(n+1)) is reached. //如果元素深度达到2*ceil(lg(n+1))则选用堆排序 n := data.Len() maxDepth := 0 for i := n; i > 0; i >>= 1 {  maxDepth++ } maxDepth *= 2 quickSort(data, 0, n, maxDepth)}
//快速排序//它这里会自动选择是用堆排序还是插入排序还是快速排序,快速排序就是func quickSort(data Interface, a, b, maxDepth int) { //如果切片元素少于十二个则使用希尔插入法 for b-a > 12 { // Use ShellSort for slices <= 12 elements  if maxDepth == 0 {   heapSort(data, a, b) //堆排序方法,a=0,b=n   return  }  maxDepth--  mlo, mhi := doPivot(data, a, b)  // Avoiding recursion on the larger subproblem guarantees  // a stack depth of at most lg(b-a).  if mlo-a < b-mhi {   quickSort(data, a, mlo, maxDepth)   a = mhi // i.e., quickSort(data, mhi, b)  } else {   quickSort(data, mhi, b, maxDepth)   b = mlo // i.e., quickSort(data, a, mlo)  } } if b-a > 1 {  // Do ShellSort pass with gap 6  // It could be written in this simplified form cause b-a <= 12  for i := a + 6; i < b; i++ {   if data.Less(i, i-6) {    data.Swap(i, i-6)   }  }  insertionSort(data, a, b) }}
//堆排序func heapSort(data Interface, a, b int) { first := a lo := 0 hi := b - a // Build heap with greatest element at top. //构建堆结构,最大的元素的顶部,就是构建大根堆 for i := (hi - 1) / 2; i >= 0; i-- {  siftDown(data, i, hi, first) } // Pop elements, largest first, into end of data. //把first插入到data的end结尾 for i := hi - 1; i >= 0; i-- {  data.Swap(first, first+i) //数据交换  siftDown(data, lo, i, first) //堆重新筛选 }}
// siftDown implements the heap property on data[lo, hi).// first is an offset into the array where the root of the heap lies.func siftDown(data Interface, lo, hi, first int) { //hi为数组的长度 //这里有一种做法是把跟元素给取到存下来,但是为了方法更抽象,省掉了这部,取而代之的是在swap的时候进行相互交换 root := lo //根元素的下标 for {  child := 2*root + 1 //左叶子结点下标  //控制for循环介绍,这种写法更简洁,可以查看我写的堆排序的文章  if child >= hi {    break  }  //防止数组下标越界,判断左孩子和右孩子那个大  if child+1 < hi && data.Less(first+child, first+child+1) {    child++  }  //判断最大的孩子和根元素之间的关系  if !data.Less(first+root, first+child) {   return  }  //如果上面都 满足,则进行数据交换  data.Swap(first+root, first+child)  root = child }}

这个包中还有很多方法,这个包实现了很多方法,比如排序反转,二分搜索。排序通过 quickSort()这个方法来控制该调用快排还是堆排。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对AIDI的支持。


  • 上一条:
    Go语言程序查看和诊断工具详解
    下一条:
    Go语言排序算法之插入排序与生成随机数详解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2017-09
    • 2020-03
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-12
    • 2021-01
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    • 2024-05
    • 2024-06
    • 2024-07
    • 2024-08
    • 2024-11
    • 2025-02
    • 2025-04
    • 2025-05
    • 2025-06
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客