实际排序示例
现实世界中的排序场景
graph TD
A[实际排序] --> B[数据结构]
A --> C[性能优化]
A --> D[复杂排序逻辑]
对复杂数据结构进行排序
学生记录排序
package main
import (
"fmt"
"sort"
)
type Student struct {
Name string
Grade int
Score float64
}
type ByGradeAndScore []Student
func (s ByGradeAndScore) Len() int { return len(s) }
func (s ByGradeAndScore) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s ByGradeAndScore) Less(i, j int) bool {
if s[i].Grade == s[j].Grade {
return s[i].Score > s[j].Score
}
return s[i].Grade < s[j].Grade
}
func main() {
students := []Student{
{"Alice", 10, 95.5},
{"Bob", 9, 88.0},
{"Charlie", 10, 92.3},
}
sort.Sort(ByGradeAndScore(students))
fmt.Println(students)
}
性能优化的排序
对大型数据集进行排序
func sortLargeDataset(data []int) {
sort.Slice(data, func(i, j int) bool {
return data[i] < data[j]
})
}
排序策略比较
场景 |
最佳方法 |
时间复杂度 |
内存使用 |
小型数据集 |
sort.Ints() |
O(n log n) |
低 |
中型数据集 |
sort.Slice() |
O(n log n) |
中等 |
大型数据集 |
自定义接口 |
O(n log n) |
高 |
高级排序技术
对大型集合进行并行排序
func parallelSort(data []int, workers int) {
chunks := splitData(data, workers)
var wg sync.WaitGroup
for _, chunk := range chunks {
wg.Add(1)
go func(c []int) {
defer wg.Done()
sort.Ints(c)
}(chunk)
}
wg.Wait()
// 合并已排序的块
}
使用自定义比较器进行排序
func sortWithCustomComparator(items []string) {
sort.Slice(items, func(i, j int) bool {
return len(items[i]) < len(items[j])
})
}
LabEx 建议
LabEx 建议练习这些排序技术,以培养在 Go 语言中强大的排序技能。
关键要点
- 根据数据类型选择正确的排序方法
- 为性能优化排序
- 理解不同排序方法之间的权衡
排序中的错误处理
func safeSorting(data []int) error {
if len(data) == 0 {
return errors.New("空数据集")
}
sort.Ints(data)
return nil
}