关于go:Go-语言中排序的-3-种方法

5次阅读

共计 1766 个字符,预计需要花费 5 分钟才能阅读完成。

原文链接: 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 string
    Age  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 string
    Age  int
}

// ByAge implements sort.Interface based on the Age field.
type ByAge []Person

func (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-a…

举荐浏览:

  • Go 语言 map 是并发平安的吗?
  • Go 语言切片是如何扩容的?
  • Go 语言数组和切片的区别
  • Go 语言 new 和 make 关键字的区别
  • 为什么 Go 不反对 []T 转换为 []interface
  • 为什么 Go 语言 struct 要应用 tags
正文完
 0