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

Go 语言中排序的 3 种方法

原文链接: Go 语言中排序的 3 种方法

在写代码过程中,排序是经常会遇到的需求,本文会介绍三种常用的方法。

废话不多说,下面正文开始。

使用标准库

根据场景直接使用标准库中的方法,比如:

  • sort.Ints
  • sort.Float64s
  • sort.Strings

举个例子:

s := []int{4, 2, 3, 1}
sort.Ints(s)
fmt.Println(s) // [1 2 3 4]

自定义比较器

使用 sort.Slice 方法排序时,可以自定义比较函数 less(i, j int) bool,这样就可以根据需要按不同的字段进行排序。

如果想要稳定排序的话,就使用 sort.SliceStable 方法。

举个例子:

family := []struct {Name stringAge  int
}{{"Alice", 23},{"David", 2},{"Eve", 2},{"Bob", 25},
}// Sort by age, keeping original order or equal elements.
sort.SliceStable(family, func(i, j int) bool {return family[i].Age < family[j].Age
})
fmt.Println(family) // [{David 2} {Eve 2} {Alice 23} {Bob 25}]

自定义数据结构

使用 sort.Sort 或者 sort.Stable 方法,它们可以对任意实现了 sort.Interface 的数据结构排序。

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)
}

意思就是说,只要某一个数据结构实现了 Len() intLess(i, j int) boolSwap(i, j int) 这三个方法,那么就可以使用 sort.Sort 来排序。

举个例子:

type Person struct {Name stringAge  int
}// ByAge implements sort.Interface based on the Age field.
type ByAge []Personfunc (a ByAge) Len() int           { return len(a) }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }func main() {family := []Person{{"Alice", 23},{"Eve", 2},{"Bob", 25},}sort.Sort(ByAge(family))fmt.Println(family) // [{Eve 2} {Alice 23} {Bob 25}]
}

字典排序

我们都知道,字典是无序的,具体原因可以看之前写的这篇文章 Go 语言 map 如何顺序读取?

如果想要字典按 key 或者 value 排序的话,可以这样做。

m := map[string]int{"Alice": 2, "Cecil": 1, "Bob": 3}keys := make([]string, 0, len(m))
for k := range m {keys = append(keys, k)
}
sort.Strings(keys)for _, k := range keys {fmt.Println(k, m[k])
}
// Output:
// Alice 2
// Bob 3
// Cecil 1

以上就是本文的全部内容,如果觉得还不错的话欢迎点赞转发关注,感谢支持。


参考文章:

  • https://yourbasic.org/golang/how-to-sort-in-go/#performance-and-implementation

推荐阅读:

  • Go 语言 map 是并发安全的吗?
  • Go 语言切片是如何扩容的?
  • Go 语言数组和切片的区别
  • Go 语言 new 和 make 关键字的区别
  • 为什么 Go 不支持 []T 转换为 []interface
  • 为什么 Go 语言 struct 要使用 tags
http://www.lryc.cn/news/129789.html

相关文章:

  • 12----Emoji表情
  • C++四种强制类型转换
  • git仓库新建上传记录
  • flutter调用so
  • c#依赖注入
  • Django框架使用定时器-APScheduler实现定时任务:django实现简单的定时任务
  • Go学习笔记之数据类型
  • Spring Cloud 微服务
  • SpringBoot属性配置
  • 算法通关村第十关 | 归并排序
  • SpringBoot3集成Kafka
  • css学习1
  • rust踩雷笔记(1)——切片传参和解引用赋值
  • 安全 1自测
  • 寻路算法小游戏
  • CSS基础 知识点总结
  • 自动执行探索性数据分析 (EDA),更快、更轻松地理解数据
  • 【自定义系统服务】【android13】添加自定义java系统服务
  • 【Sklearn】基于随机梯度下降算法的数据分类预测(Excel可直接替换数据)
  • 44、TCP报文(二)
  • 目标检测(Object Detection)
  • vue中实现文字检索时候将搜索内容标红
  • PCL protocol composition logic
  • 聊聊看React和Vue的区别
  • OSPF在广播类型的网络拓扑中DR和BDR的选举
  • 系统学习Linux-Mariadb高可用MHA
  • 慢SQL的原因
  • php正则替换文章的图片
  • 57 | TAPTAP客户端分析
  • 开源了一套基于springboot+vue+uniapp的商城,包含分类、sku、商户管理、分销、会员、适合企业或个人二次开发