vault backup: 2026-05-13 15:47:15
This commit is contained in:
+22
-10
@@ -204,27 +204,39 @@ Go 的排序功能集中在 `sort` 包中,支持对整型切片、字符串切
|
|||||||
### 内建排序
|
### 内建排序
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import "sort"
|
import (
|
||||||
|
"cmp" // slices.Sort 需要
|
||||||
|
"sort"
|
||||||
|
)
|
||||||
|
|
||||||
nums := []int{3, 1, 4, 1, 5, 9, 2}
|
nums := []int{3, 1, 4, 1, 5, 9, 2}
|
||||||
strs := []string{"banana", "apple", "cherry"}
|
strs := []string{"banana", "apple", "cherry"}
|
||||||
|
|
||||||
// 升序排列
|
// sort 包内建排序
|
||||||
sort.Ints(nums) // [1, 1, 2, 3, 4, 5, 9]
|
sort.Ints(nums) // [1, 1, 2, 3, 4, 5, 9]
|
||||||
sort.Strings(strs) // ["apple", "banana", "cherry"]
|
sort.Strings(strs) // ["apple", "banana", "cherry"]
|
||||||
sort.IntsAreSorted(nums) // true(仅检查,不修改)
|
sort.IntsAreSorted(nums) // true(仅检查,不修改)
|
||||||
|
|
||||||
// 对已有切片排序(原地修改)
|
// slices.Sort(Go 1.21+)— 基本类型一行搞定
|
||||||
sort.Slice(nums, func(i, j int) bool {
|
slices.Sort(nums) // [1, 1, 2, 3, 4, 5, 9]
|
||||||
return nums[i] < nums[j] // 升序
|
slices.Sort(strs) // ["apple", "banana", "cherry"]
|
||||||
})
|
|
||||||
|
|
||||||
// 降序排列
|
|
||||||
sort.Sort(sort.Reverse(sort.IntSlice(nums)))
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
> [!info] 🔑 slices.Sort vs sort.Slice
|
||||||
|
>
|
||||||
|
> | 维度 | `slices.Sort` | `sort.Slice` |
|
||||||
|
> |------|-------------|-------------|
|
||||||
|
> | 来源 | `cmp/slices`(Go 1.21+) | `sort`(Go 1.0) |
|
||||||
|
> | 类型约束 | `cmp.Ordered`(基本比较类型) | `any`(任意类型) |
|
||||||
|
> | 自定义排序 | ❌ 不支持 | ✅ 传入比较函数 |
|
||||||
|
> | 性能 | 内部高度优化 | 闭包间接调用有开销 |
|
||||||
|
>
|
||||||
|
> **选择原则**:基本类型简单排序 → `slices.Sort`;结构体多字段 / 降序 / 旧版 Go → `sort.Slice`。
|
||||||
|
|
||||||
### 自定义排序
|
### 自定义排序
|
||||||
|
|
||||||
|
#### sort.Slice
|
||||||
|
|
||||||
```go
|
```go
|
||||||
type Pair struct {
|
type Pair struct {
|
||||||
Key string
|
Key string
|
||||||
@@ -266,7 +278,7 @@ sort.SliceStable(students, func(i, j int) bool {
|
|||||||
```
|
```
|
||||||
|
|
||||||
> [!tip] 🔑 算法复杂度
|
> [!tip] 🔑 算法复杂度
|
||||||
> - `sort.Ints` / `sort.Strings`:内联实现,使用插排+堆排混合策略,均摊 O(n log n),常数极小
|
> - `sort.Ints` / `sort.Strings` / `slices.Sort`:内联实现,使用插排+堆排混合策略,均摊 O(n log n),常数极小
|
||||||
> - `sort.Slice`:基于 quicksort,O(n log n),但自定义比较函数有间接调用开销
|
> - `sort.Slice`:基于 quicksort,O(n log n),但自定义比较函数有间接调用开销
|
||||||
> - `sort.Stable`:内层使用稳定排序(如 merge sort),最坏情况仍 O(n log n)
|
> - `sort.Stable`:内层使用稳定排序(如 merge sort),最坏情况仍 O(n log n)
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user