Go 语言中排序的三种方法

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

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

Go 语言中排序的三种方法

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

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

使用标准库

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

  • 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() int,Less(i, j int) bool和Swap(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-and-implementation

©本文为清一色官方代发,观点仅代表作者本人,与清一色无关。清一色对文中陈述、观点判断保持中立,不对所包含内容的准确性、可靠性或完整性提供任何明示或暗示的保证。本文不作为投资理财建议,请读者仅作参考,并请自行承担全部责任。文中部分文字/图片/视频/音频等来源于网络,如侵犯到著作权人的权利,请与我们联系(微信/QQ:1074760229)。转载请注明出处:清一色财经

(0)
打赏 微信扫码打赏 微信扫码打赏 支付宝扫码打赏 支付宝扫码打赏
清一色的头像清一色管理团队
上一篇 2023年8月16日 17:05
下一篇 2023年8月16日 17:08

相关推荐

发表评论

登录后才能评论

联系我们

在线咨询:1643011589-QQbutton

手机:13798586780

QQ/微信:1074760229

QQ群:551893940

工作时间:工作日9:00-18:00,节假日休息

关注微信