当前位置: 首页 > news >正文

golang内置包里面的sort.Slice 切片排序函数使用示例

go语言里面用的最多的数据类型应该是切片Slice了, 今天就给大家介绍这个go内置包里面的切片排序函数的使用方法

函数原型  func Slice(x any, less func(i, j int) bool)

参数说明 这个函数有2个参数, 第一个是你要进行排序的slice切片,地个要传递一个函数,这个函数就是你要对你的数据进行怎么样的排序。

示例代码:

var s1 = []int{133,144,21,69,83,37,56,38,68,123,23,89,170,8,76,120} // 这个就是要排序的int切片

sort.Slice(s1, func(i, j int) bool { return s1[i] > s1[j] }) 

// 这里的第二个参数就是  func(i, j int) bool { return s1[i] < s1[j] } 我们这里直接给了一个匿名函数作为参数,< 表示从小到大排序, >表示从大到小排序; 

//这里的这个函数因为是切片类型 其就是引用数据类型,所以不需要接收数据

怎么样,是不是很简单, 其他2个函数用法可参考后面的源码使用。。。。

Slice排序函数源码参考, 路径 /src/sort/slice.go  


// Slice sorts the slice x given the provided less function.
// It panics if x is not a slice.
//
// The sort is not guaranteed to be stable: equal elements
// may be reversed from their original order.
// For a stable sort, use SliceStable.
//
// The less function must satisfy the same requirements as
// the Interface type's Less method.
func Slice(x any, less func(i, j int) bool) {rv := reflectlite.ValueOf(x)swap := reflectlite.Swapper(x)length := rv.Len()limit := bits.Len(uint(length))pdqsort_func(lessSwap{less, swap}, 0, length, limit)
}// SliceStable sorts the slice x using the provided less
// function, keeping equal elements in their original order.
// It panics if x is not a slice.
//
// The less function must satisfy the same requirements as
// the Interface type's Less method.
func SliceStable(x any, less func(i, j int) bool) {rv := reflectlite.ValueOf(x)swap := reflectlite.Swapper(x)stable_func(lessSwap{less, swap}, rv.Len())
}// SliceIsSorted reports whether the slice x is sorted according to the provided less function.
// It panics if x is not a slice.
func SliceIsSorted(x any, less func(i, j int) bool) bool {rv := reflectlite.ValueOf(x)n := rv.Len()for i := n - 1; i > 0; i-- {if less(i, i-1) {return false}}return true
}

http://www.lryc.cn/news/343708.html

相关文章:

  • Golang | Leetcode Golang题解之第70题爬楼梯
  • 区块链 | NFT 相关论文:Preventing Content Cloning in NFT Collections(三)
  • Unity技术学习:渲染大量物体的解决方案,外加RenderMesh、RenderMeshInstanced、RenderMeshIndirect的简单使用
  • [数据概念|方案实操][最新]数据资产入表4月速递
  • C++中使用Multimap和Vector管理和展示数据
  • Java---类和方法的再学习
  • C语言每日一练(12、水仙花数)
  • HTML5实现酷炫个人产品推广、工具推广、信息推广、个人主页、个人介绍、酷炫官网、门户网站模板源码
  • 系统如何做好安全加固?
  • 对NI系统和PLC系统的应用比较
  • 微服务架构中的挑战及应对方式:Outbox 模式
  • 使用Docker安装MySQL5.7.36
  • 【PyTorch】6-可视化(网络结构可视化、CNN可视化、TensorBoard、wandb)
  • C++容器——map和pair对组
  • MVC和DDD的贫血和充血模型对比
  • 如何利用AI提高内容生产效率?
  • C++ stack、queue以及deque
  • 科沃斯,「扫地茅」荣光恐难再现
  • 双向BFS算法学习
  • C++从入门到精通---模版
  • Unity数据持久化之Json
  • LeetCode 35.搜索插入位置
  • 速来get!多微信聚合聊天功能大揭秘!
  • 【跟我学RISC-V】(一)认识RISC-V指令集并搭建实验环境
  • 如何使用google.protobuf.Struct?
  • Vue3 + TS + Element-Plus 封装的 Dialog 弹窗组件
  • 大数据技术概述_4.大数据的应用领域
  • ABB RobotStudio学习记录(一)新建工作站
  • 雷达通信一体化(含WCSP2023会议论文集学习)
  • 特斯拉擎天柱机器人:工厂自动化的未来