Practical Sorting Examples
Real-World Sorting Scenarios
Sorting is a critical operation in many programming tasks. This section explores practical sorting examples that demonstrate the versatility of Go's sorting capabilities.
graph LR
A[Sorting Scenarios] --> B[Numeric Sorting]
A --> C[Struct Sorting]
A --> D[Complex Data Sorting]
Example 1: Sorting Complex Structs
Product Inventory Sorting
package main
import (
"fmt"
"sort"
)
type Product struct {
Name string
Price float64
Quantity int
}
// Sort by Price (Ascending)
type ByPrice []Product
func (a ByPrice) Len() int { return len(a) }
func (a ByPrice) Less(i, j int) bool { return a[i].Price < a[j].Price }
func (a ByPrice) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func main() {
inventory := []Product{
{"Laptop", 1200.50, 10},
{"Smartphone", 800.75, 25},
{"Tablet", 500.25, 15},
}
sort.Sort(ByPrice(inventory))
for _, product := range inventory {
fmt.Printf("%s: $%.2f (Qty: %d)\n",
product.Name, product.Price, product.Quantity)
}
}
Example 2: Multi-Criteria Sorting
package main
import (
"fmt"
"sort"
)
type Employee struct {
Name string
Salary float64
Performance float64
}
// Sort by Performance, then by Salary
func sortEmployees(employees []Employee) {
sort.Slice(employees, func(i, j int) bool {
if employees[i].Performance == employees[j].Performance {
return employees[i].Salary > employees[j].Salary
}
return employees[i].Performance > employees[j].Performance
})
}
func main() {
employees := []Employee{
{"Alice", 75000, 9.5},
{"Bob", 65000, 9.5},
{"Charlie", 80000, 8.7},
}
sortEmployees(employees)
for _, emp := range employees {
fmt.Printf("%s: Performance %.1f, Salary $%.2f\n",
emp.Name, emp.Performance, emp.Salary)
}
}
Sorting Techniques Comparison
Sorting Method |
Use Case |
Flexibility |
Performance |
sort.Ints() |
Simple numeric sorting |
Low |
Highest |
sort.Interface |
Complex struct sorting |
High |
Moderate |
sort.Slice() |
Inline sorting logic |
Medium |
Good |
Advanced Sorting Strategies
Key Sorting Considerations
- Use
sort.Stable()
to maintain original order
- Implement custom
Less()
method for complex comparisons
- Consider performance for large datasets
- Minimize comparison operations
- Use appropriate sorting method
- Avoid unnecessary sorting
- Profile your sorting logic
Error Handling in Sorting
func safeSortSlice(data []int) {
defer func() {
if r := recover(); r != nil {
fmt.Println("Sorting failed:", r)
}
}()
sort.Ints(data)
}
LabEx recommends mastering these sorting techniques to handle diverse sorting requirements efficiently in Go programming.