golang学习笔记:标准库sort
Go 语言的 sort 包提供了切片和用户定义集合的排序功能。
常用方法
基本排序操作
1.内置类型排序
// 整数切片排序
ints := []int{4, 2, 7, 1, 9, 3}
sort.Ints(ints) // [1 2 3 4 7 9]// 检查是否已排序
isSorted := sort.IntsAreSorted(ints) // true// 浮点数切片排序
floats := []float64{3.2, 1.8, 5.4, 2.1}
sort.Float64s(floats) // [1.8 2.1 3.2 5.4]// 字符串切片排序
strings := []string{"banana", "apple", "cherry"}
sort.Strings(strings) // ["apple" "banana" "cherry"]
2.反向排序
ints := []int{4, 2, 7, 1, 9, 3}// 方法1:使用 sort.Reverse
sort.Sort(sort.Reverse(sort.IntSlice(ints)))
// [9 7 4 3 2 1]// 方法2:自定义比较函数
sort.Slice(ints, func(i, j int) bool {return ints[i] > ints[j] // 降序
})
自定义排序
1.使用sort.Slice
type Person struct {Name stringAge int
}people := []Person{{"Alice", 25},{"Bob", 30},{"Charlie", 20},
}// 按年龄排序
sort.Slice(people, func(i, j int) bool {return people[i].Age < people[j].Age
})
// [{Charlie 20} {Alice 25} {Bob 30}]// 按姓名排序
sort.Slice(people, func(i, j int) bool {return people[i].Name < people[j].Name
})
// [{Alice 25} {Bob 30} {Charlie 20}]
2.使用sort.SliceStable
// 稳定排序(保持相等元素的原始顺序)
people := []Person{{"Alice", 25},{"Bob", 30},{"Charlie", 25}, // 与 Alice 年龄相同
}sort.SliceStable(people, func(i, j int) bool {return people[i].Age < people[j].Age
})
// 保持 Alice 和 Charlie 的原始相对顺序
3.实现sort.Interface
// 自定义类型实现 sort.Interface
type ByAge []Personfunc (a ByAge) Len() int { return len(a) }
func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }// 使用
people := []Person{{"Alice", 25},{"Bob", 30},{"Charlie", 20},
}
sort.Sort(ByAge(people))
// [{Charlie 20} {Alice 25} {Bob 30}]
搜索操作
1.二分查找
// 在已排序的切片中查找
ints := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}// 查找元素位置
index := sort.SearchInts(ints, 5) // 4
index = sort.SearchInts(ints, 10) // 9 (未找到,返回可插入位置)// 通用二分查找
index = sort.Search(len(ints), func(i int) bool {return ints[i] >= 5 // 查找第一个 >= 5 的元素
}) // 4
sort和slices
sort 包和 slices 包确实有很多功能重叠。sort包在Go1.0就存在,传统的排序方式;slices包在Go1.18引入,基于泛型的现代方式。
| 功能 | sort 包 | slices 包 | 推荐 |
|---|---|---|---|
| 排序 | sort.Ints() | slices.Sort() | ✅ slices |
| 检查排序 | sort.IntsAreSorted() | slices.IsSorted() | ✅ slices |
| 二分查找 | sort.SearchInts() | slices.BinarySearch() | ✅ slices |
| 自定义排序 | sort.Slice() | slices.SortFunc() | ✅ slices |
| 稳定排序 | sort.SliceStable() | slices.SortStableFunc() | ✅ slices |
| 查找元素 | 需要手动实现 | slices.Index() | ✅ slices |
| 插入删除 | 需要手动实现 | slices.Insert(), Delete() | ✅ slices |
