Standard Sort Methods
Overview of Standard Sorting Methods
Golang provides several standard sorting methods that cover most common sorting scenarios. These methods are part of the sort
package and offer straightforward solutions for different data types and sorting requirements.
Basic Sorting Methods
Sorting Primitive Types
package main
import (
"fmt"
"sort"
)
func main() {
// Integer sorting
nums := []int{5, 2, 6, 3, 1}
sort.Ints(nums)
fmt.Println("Sorted integers:", nums)
// String sorting
fruits := []string{"banana", "apple", "cherry"}
sort.Strings(fruits)
fmt.Println("Sorted strings:", fruits)
// Float sorting
prices := []float64{9.99, 5.50, 7.25}
sort.Float64s(prices)
fmt.Println("Sorted floats:", prices)
}
Reverse Sorting
package main
import (
"fmt"
"sort"
)
func main() {
nums := []int{5, 2, 6, 3, 1}
sort.Sort(sort.Reverse(sort.IntSlice(nums)))
fmt.Println("Reverse sorted:", nums)
}
Sorting Methods Comparison
Method |
Type |
In-Place |
Time Complexity |
sort.Ints() |
Integer |
Yes |
O(n log n) |
sort.Strings() |
String |
Yes |
O(n log n) |
sort.Float64s() |
Float64 |
Yes |
O(n log n) |
Sorting Flow
graph TD
A[Original Slice] --> B{Sorting Method}
B --> C[Sorted Slice]
B --> D[Reverse Sorted Slice]
Custom Slice Sorting
package main
import (
"fmt"
"sort"
)
type Person struct {
Name string
Age int
}
type ByAge []Person
func (a ByAge) Len() int { return len(a) }
func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
func main() {
people := []Person{
{"Alice", 30},
{"Bob", 25},
{"Charlie", 35},
}
sort.Sort(ByAge(people))
fmt.Println("Sorted by age:", people)
}
Key Takeaways
- Golang's
sort
package provides efficient sorting methods
- Most standard sorting methods modify the slice in-place
- Custom sorting can be implemented by implementing
sort.Interface
At LabEx, we recommend mastering these standard sorting methods to efficiently manage and organize data in your Golang applications.