Golang 标准库 - 示例代码

sort

Golang 标准库 - sort

sort 包提供对切片与自定义集合的排序能力。底层是混合排序(快排 + 插入 + 堆排),日常开发推荐直接用 sort.Slice 传入比较函数,比手写 sort.Interface 简洁得多。

核心函数速查

函数 用途
sort.Ints / Float64s / Strings 基础类型升序排序
sort.Slice(s, less) 自定义比较函数排序(最常用)
sort.SliceStable(s, less) 稳定排序(相等元素保持原序)
sort.IntsAreSorted 判断是否已排序
sort.Search / SearchInts 二分查找 / 定位插入位置
sort.Reverse 反向排序包装器

可运行示例

package main

import (
	"fmt"
	"sort"
)

type Person struct {
	Name string
	Age  int
}

func main() {
	// 基础类型排序
	nums := []int{5, 2, 6, 3, 1, 4}
	sort.Ints(nums)
	fmt.Println("Ints:", nums) // [1 2 3 4 5 6]

	strs := []string{"banana", "apple", "cherry"}
	sort.Strings(strs)
	fmt.Println("Strings:", strs) // [apple banana cherry]

	// 自定义排序:按年龄
	people := []Person{{"Alice", 30}, {"Bob", 25}, {"Charlie", 35}}
	sort.Slice(people, func(i, j int) bool {
		return people[i].Age < people[j].Age
	})
	fmt.Println("按年龄排序:", people)

	// 二分搜索
	sorted := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
	idx := sort.SearchInts(sorted, 5)
	fmt.Printf("5 的位置: %d\n", idx) // 4

	// 通用 Search:第一个 >=6 的位置
	idx = sort.Search(len(sorted), func(i int) bool { return sorted[i] >= 6 })
	fmt.Printf("第一个 >=6 的位置: %d\n", idx) // 5
}

站内深度阅读(原理篇)

用 sort.Ints 是基本功,面试官常让你手写排序:

相关阅读

🛒 站长推荐(京东联盟)

以上链接含京东联盟推广代码;通过链接购买本站可能获得少量佣金,不影响你的购买价格。

📮 关注公众号「Go2AI之路」
Go2AI之路 公众号二维码

每周更新 Go + AI 应用开发实战:AI 面试官完整项目、MCP、Agent 工程化,完整源码随文章首发。

微信扫码,或搜索「Go2AI之路」关注,第一时间获取系列更新与源码,不再错过任何一篇。

如有疑问关注公众号给我留言
wx

关注公众号

©2017-2026 鲁ICP备17023316号-1 Powered by Hugo · 隐私政策