Go语言标准库sort包排序用法详解
Go语言标准库提供了强大的 sort 包,支持对切片进行排序。无论是简单的整数、字符串,还是复杂的自定义结构体,均可通过实现特定接口或调用内置函数完成操作。
掌握基础:理解sort.Interface接口
Go语言的排序机制核心在于实现 sort.Interface 接口。任何想要被排序的集合(通常是切片),必须满足以下三个基本方法:
Len() int:返回集合中的元素数量。Less(i, j int) bool:判断索引i处的元素是否应排在索引j处元素之前。Swap(i, j int):交换索引i和j处的元素。
以下是该接口的定义示例,展示了排序所需的底层逻辑:
// A type, typically a collection, that satisfies sort.Interface can be
// sorted by the routines in this package. The methods require that the
// elements of the collection be enumerated by an integer index.
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)
}
第1步:为简单数据类型实现排序逻辑
虽然 sort 包已提供常用类型的内置方法,但手动实现接口是理解其原理的最佳方式,适用于需要自定义比较逻辑的场景。
目的:将自定义类型 IntSlice 转换为可排序对象,并对整数切片进行升序排列。
操作:
- 定义一个基于切片的自定义类型
type IntSlice []int。 - 为该类型实现
Len、Swap和Less方法。 - 调用
sort.Sort并传入实现了对接口的类型实例。
代码示例:
package main
import (
"fmt"
"sort"
)
type IntSlice []int
func (s IntSlice) Len() int { return len(s) }
func (s IntSlice) Swap(i, j int){ s[i], s[j] = s[j], s[i] }
func (s IntSlice) Less(i, j int) bool { return s[i] < s[j] }
func main() {
a := []int{4,3,2,1,5,9,8,7,6}
sort.Sort(IntSlice(a))
fmt.Println("After sorted: ", a)
}
第2步:直接使用内置便捷函数
对于常见的 []int 和 []string,Go语言已经预定义了 IntSlice 和 StringSlice 类型及对应的排序函数,无需手动重复实现接口。
目的:快速对整数和字符串切片进行排序,包括执行逆向排序。
操作:
- 使用
sort.Ints直接对整型切片排序。 - 使用
sort.Strings直接对字符串切片排序。 - 使用
sort.Reverse包装切片类型以实现降序排列。
代码示例:
package main
import (
"fmt"
"sort"
)
func main() {
a := []int{3, 5, 4, -1, 9, 11, -14}
sort.Ints(a)
fmt.Println(a)
ss := []string{"surface", "ipad", "mac pro", "mac air", "think pad", "idea pad"}
sort.Strings(ss)
fmt.Println(ss)
// 逆序排序
sort.Sort(sort.Reverse(sort.StringSlice(ss)))
fmt.Printf("After reverse: %v\n", ss)
}
第3步:使用Reverse进行逆序排序
如果需要降序排列,手动修改 Less 函数较为繁琐。推荐使用 sort.Reverse 装饰器,它能自动反转比较逻辑。
目的:对现有切片执行降序排列。
操作:
- 创建目标切片(如
[]int)。 - 使用
sort.Reverse包裹对应的 Slice 类型(如sort.IntSlice)。 - 将包裹后的对象传给
sort.Sort。
代码示例:
package main
import (
"fmt"
"sort"
)
func main() {
a := []int{4,3,2,1,5,9,8,7,6}
sort.Sort(sort.Reverse(sort.IntSlice(a)))
fmt.Println("After reversed: ", a)
}
第4步:执行稳定排序以保留原始顺序
标准的 sort.Sort 算法不保证排序稳定性。当排序关键字相同时,若需保持它们在原切片中的相对位置,应使用 sort.Stable。
目的:按年龄排序人员列表,确保同龄人的姓名保持原有输入顺序。
操作:
- 定义结构体
person及其对应的切片类型personSlice。 - 为
personSlice实现sort.Interface,在Less中指定比较字段(如Age)。 - 使用
sort.Stable替代sort.Sort执行排序。
代码示例:
package main
import (
"fmt"
"sort"
)
type person struct {
Name string
Age int
}
type personSlice []person
func (s personSlice) Len() int { return len(s) }
func (s personSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s personSlice) Less(i, j int) bool { return s[i].Age < s[j].Age }
func main() {
a := personSlice {
{Name: "AAA", Age: 55},
{Name: "BBB", Age: 22},
{Name: "CCC", Age: 0},
{Name: "DDD", Age: 22},
{Name: "EEE", Age: 11},
}
sort.Stable(a)
fmt.Println(a)
}
以上就是Go语言编程使用sort来排序示例详解的详细内容,更多关于Go语言sort排序的资料请关注本站其它相关文章!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













