Go语言标准库sort包排序用法详解

Jasper
Jasper
发布时间:2026-10-16| 6人浏览过
原创

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 转换为可排序对象,并对整数切片进行升序排列。

操作:

  1. 定义一个基于切片的自定义类型 type IntSlice []int。
  2. 为该类型实现 Len、Swap 和 Less 方法。
  3. 调用 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 类型及对应的排序函数,无需手动重复实现接口。

目的:快速对整数和字符串切片进行排序,包括执行逆向排序。

操作:

  1. 使用 sort.Ints 直接对整型切片排序。
  2. 使用 sort.Strings 直接对字符串切片排序。
  3. 使用 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 装饰器,它能自动反转比较逻辑。

目的:对现有切片执行降序排列。

操作:

  1. 创建目标切片(如 []int)。
  2. 使用 sort.Reverse 包裹对应的 Slice 类型(如 sort.IntSlice)。
  3. 将包裹后的对象传给 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。

目的:按年龄排序人员列表,确保同龄人的姓名保持原有输入顺序。

操作:

  1. 定义结构体 person 及其对应的切片类型 personSlice。
  2. 为 personSlice 实现 sort.Interface,在 Less 中指定比较字段(如 Age)。
  3. 使用 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排序的资料请关注本站其它相关文章!

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。