Practical Sorting Examples
Real-World Sorting Scenarios
graph TD
A[Practical Sorting] --> B[Data Structures]
A --> C[Performance Optimization]
A --> D[Complex Sorting Logic]
Sorting Complex Data Structures
Student Record Sorting
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)
}
Large Dataset Sorting
func sortLargeDataset(data []int) {
sort.Slice(data, func(i, j int) bool {
return data[i] < data[j]
})
}
Sorting Strategies Comparison
Scenario |
Best Method |
Time Complexity |
Memory Usage |
Small Dataset |
sort.Ints() |
O(n log n) |
Low |
Medium Dataset |
sort.Slice() |
O(n log n) |
Moderate |
Large Dataset |
Custom Interface |
O(n log n) |
High |
Advanced Sorting Techniques
Parallel Sorting for Large Collections
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()
// Merge sorted chunks
}
Sorting with Custom Comparators
func sortWithCustomComparator(items []string) {
sort.Slice(items, func(i, j int) bool {
return len(items[i]) < len(items[j])
})
}
LabEx Recommendation
LabEx suggests practicing these sorting techniques to develop robust sorting skills in Go.
Key Takeaways
- Choose the right sorting method based on data type
- Optimize sorting for performance
- Understand trade-offs between different sorting approaches
Error Handling in Sorting
func safeSorting(data []int) error {
if len(data) == 0 {
return errors.New("empty dataset")
}
sort.Ints(data)
return nil
}