Practical Sorting Examples
Real-World Sorting Scenarios
1. Sorting Complex Structs
type Product struct {
Name string
Price float64
Quantity int
}
type ByPriceAndQuantity []Product
func (p ByPriceAndQuantity) Len() int {
return len(p)
}
func (p ByPriceAndQuantity) Less(i, j int) bool {
// Multi-criteria sorting
if p[i].Price == p[j].Price {
return p[i].Quantity > p[j].Quantity
}
return p[i].Price < p[j].Price
}
func (p ByPriceAndQuantity) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}
Sorting Strategies
graph TD
A[Sorting Strategies] --> B[Price Ascending]
A --> C[Quantity Descending]
A --> D[Complex Comparisons]
2. Custom String Sorting
type CustomStringSlice []string
func (c CustomStringSlice) Len() int {
return len(c)
}
func (c CustomStringSlice) Less(i, j int) bool {
// Custom string comparison logic
return len(c[i]) < len(c[j])
}
func (c CustomStringSlice) Swap(i, j int) {
c[i], c[j] = c[j], c[i]
}
Sorting Method |
Time Complexity |
Memory Usage |
Standard Sort |
O(n log n) |
Low |
Custom Sort |
O(n log n) |
Moderate |
3. Reverse Sorting Implementation
type ReverseSort struct {
sort.Interface
}
func (r ReverseSort) Less(i, j int) bool {
return r.Interface.Less(j, i)
}
func main() {
numbers := []int{5, 2, 8, 1, 9}
sort.Sort(ReverseSort{sort.IntSlice(numbers)})
}
Advanced Sorting Techniques
graph TD
A[Advanced Sorting] --> B[Stable Sorting]
A --> C[Partial Sorting]
A --> D[Concurrent Sorting]
4. Sorting with Type Aliases
type UserScores []struct {
Name string
Score int
}
func (u UserScores) Len() int {
return len(u)
}
func (u UserScores) Less(i, j int) bool {
return u[i].Score > u[j].Score
}
func (u UserScores) Swap(i, j int) {
u[i], u[j] = u[j], u[i]
}
Best Practices
- Choose appropriate sorting method
- Consider performance implications
- Use type aliases for clarity
- Implement custom comparison logic carefully
LabEx recommends exploring these practical sorting techniques to enhance your Golang programming skills.