Go 语言入门很简单:sort 包

举报
宇宙之一粟 发表于 2022/04/24 11:54:49 2022/04/24
1.2k+ 0 0
【摘要】 引言排序算法一直是很经常使用的功能。Go 语言标准库为我们提供了方便快捷的 sort 包 ,这个包实现了四种基本排序算法:插入排序、归并排序、堆排序和快速排序。Go 的 sort 包实现了内置和用户定义类型的排序。我们将首先查看内置函数的排序。常见数据类型排序为了方便对常用数据类型的操作,sort 包提供了对 []int 切片、[]float64 切片和 []string 切片完整支持:so...

引言

排序算法一直是很经常使用的功能。Go 语言标准库为我们提供了方便快捷的 sort 包 ,这个包实现了四种基本排序算法:插入排序、归并排序、堆排序和快速排序。

Go 的 sort 包实现了内置和用户定义类型的排序。我们将首先查看内置函数的排序。

常见数据类型排序

为了方便对常用数据类型的操作,sort 包提供了对 []int 切片、[]float64 切片和 []string 切片完整支持:

来看一个简单例子:

package main

import (
	"fmt"
	"sort"
)

func main() {

	s := []int{2022, 2008, 2012, 2025}
	sort.Ints(s)
	fmt.Println("Sorted Ints: ", s)

	f := []float64{3.14159, 2.14, 19.99}
	sort.Float64s(f)
	fmt.Println("Sorted Floats: ", f)

	strings := []string{"Kyrie", "Marry", "Allen", "Suzan"}
	sort.Strings(strings)
	fmt.Println("Sorted Strings: ", strings)

}

运行该代码:

$ go run main.go
Sorted Ints:  [2008 2012 2022 2025]
Sorted Floats:  [2.14 3.14159 19.99]
Sorted Strings:  [Allen Kyrie Marry Suzan]

sort 提供的几个常见函数:

请注意,排序是就地的,因此它会更改给定的切片并且不会返回新切片。

如果我们想要创建新的,排序的切片,我们使用内置的 makecopy 函数。如下所示:

package main

import (
	"fmt"
	"sort"
)

func main() {

	s := []int{2022, 2008, 2012, 2025}
	// sort.Ints(s)
	fmt.Println("unSorted Ints: ", s)

	sortedInt := make([]int, len(s))
	copy(sortedInt, s)
	sort.Ints(sortedInt)
	fmt.Println("Sorted Ints: ", sortedInt)

}

运行该代码:

$ go run main.go
unSorted Ints:  [2022 2008 2012 2025]
Sorted Ints:  [2008 2012 2022 2025]

我们还可以使用 sort.IntsAreSorted 来检查 int 切片是否已经排序:

package main

import (
	"fmt"
	"sort"
)

func main() {

	s := []int{2022, 2008, 2012, 2025}
	// sort.Ints(s)
	fmt.Println("unSorted Ints: ", s)

	sortedInt := make([]int, len(s))
	copy(sortedInt, s)
	sort.Ints(sortedInt)
	fmt.Println("Sorted Ints: ", sortedInt)

	if sort.IntsAreSorted(sortedInt) {
		fmt.Println("s 已排序")
	} else {
		fmt.Println("s 未排序")
	}

}

运行我们的程序:

$ go run main.go
unSorted Ints:  [2022 2008 2012 2025]
Sorted Ints:  [2008 2012 2022 2025]
s 已排序

使用自定义比较器排序

  • 使用函数 sort.Slice。它使用提供的函数 less(i, jint) 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.Interface 接口,提供 Len()Less()Swap() 三个方法的实现。然后使用通用的 sort.Sortsort.Stable 函数,他们会对任何实现了 sort.Interface 接口的集合进行排序。

以下是 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)
}

来看这个例子:

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

按键或值对地图进行排序

映射是键值对的无序集合。如果需要稳定的迭代顺序,则必须维护单独的数据结构。

以下代码示例使用一个键切片按键顺序对映射进行排序。

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

总结

从本文中,我们了解了排序在 go 语言中的运用,学习了 go 语言 sort 提供的几个方法,并通过实现 sort.Interface 接口对自定义数据结构进行比较。当然,sort 的用法远远不止这些,比如降序、稳定排序。其他的留给大家自己去探索吧。

【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

作者其他文章

评论(0

抱歉,系统识别当前为高风险访问,暂不支持该操作

    全部回复

    上滑加载中

    设置昵称

    在此一键设置昵称,即可参与社区互动!

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。