Go 语言中排序的 3 种方法

打印 上一主题 下一主题

主题 911|帖子 911|积分 2735

原文链接: Go 语言中排序的 3 种方法
在写代码过程中,排序是经常会遇到的需求,本文会介绍三种常用的方法。
废话不多说,下面正文开始。
使用标准库

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

  • sort.Ints
  • sort.Float64s
  • sort.Strings
举个例子:
  1. s := []int{4, 2, 3, 1}
  2. sort.Ints(s)
  3. fmt.Println(s) // [1 2 3 4]
复制代码
自定义比较器

使用 sort.Slice 方法排序时,可以自定义比较函数 less(i, j int) bool,这样就可以根据需要按不同的字段进行排序。
如果想要稳定排序的话,就使用 sort.SliceStable 方法。
举个例子:
  1. family := []struct {
  2.     Name string
  3.     Age  int
  4. }{
  5.     {"Alice", 23},
  6.     {"David", 2},
  7.     {"Eve", 2},
  8.     {"Bob", 25},
  9. }
  10. // Sort by age, keeping original order or equal elements.
  11. sort.SliceStable(family, func(i, j int) bool {
  12.     return family[i].Age < family[j].Age
  13. })
  14. fmt.Println(family) // [{David 2} {Eve 2} {Alice 23} {Bob 25}]
复制代码
自定义数据结构

使用 sort.Sort 或者 sort.Stable 方法,它们可以对任意实现了 sort.Interface 的数据结构排序。
  1. type Interface interface {
  2.     // Len is the number of elements in the collection.
  3.     Len() int
  4.     // Less reports whether the element with
  5.     // index i should sort before the element with index j.
  6.     Less(i, j int) bool
  7.     // Swap swaps the elements with indexes i and j.
  8.     Swap(i, j int)
  9. }
复制代码
意思就是说,只要某一个数据结构实现了 Len() int,Less(i, j int) bool 和 Swap(i, j int) 这三个方法,那么就可以使用 sort.Sort 来排序。
举个例子:
  1. type Person struct {
  2.     Name string
  3.     Age  int
  4. }
  5. // ByAge implements sort.Interface based on the Age field.
  6. type ByAge []Person
  7. func (a ByAge) Len() int           { return len(a) }
  8. func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
  9. func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
  10. func main() {
  11.     family := []Person{
  12.         {"Alice", 23},
  13.         {"Eve", 2},
  14.         {"Bob", 25},
  15.     }
  16.     sort.Sort(ByAge(family))
  17.     fmt.Println(family) // [{Eve 2} {Alice 23} {Bob 25}]
  18. }
复制代码
字典排序

我们都知道,字典是无序的,具体原因可以看之前写的这篇文章 Go 语言 map 如何顺序读取?
如果想要字典按 key 或者 value 排序的话,可以这样做。
  1. m := map[string]int{"Alice": 2, "Cecil": 1, "Bob": 3}
  2. keys := make([]string, 0, len(m))
  3. for k := range m {
  4.     keys = append(keys, k)
  5. }
  6. sort.Strings(keys)
  7. for _, k := range keys {
  8.     fmt.Println(k, m[k])
  9. }
  10. // Output:
  11. // Alice 2
  12. // Bob 3
  13. // Cecil 1
复制代码
以上就是本文的全部内容,如果觉得还不错的话欢迎点赞转发关注,感谢支持。
参考文章:
推荐阅读:

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

南七星之家

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表