The sort Package
Sorting Basic Slices
The sort package provides direct sorting functions for the most common slice types -- sort.Ints, sort.Strings, and sort.Float64s -- which sort the given slice in place, ascending.
Example: Sorting Basic Slices
package main
import (
"fmt"
"sort"
)
func main() {
nums := []int{5, 2, 8, 1, 9}
sort.Ints(nums)
fmt.Println(nums)
}
Login to try C/C++/Java/PHP code in the editor
Custom Sorting with sort.Slice
sort.Slice sorts any slice according to a custom comparison function you supply, which should return true when the element at index i belongs before the element at index j.
Example: Custom Sorting with sort.Slice
package main
import (
"fmt"
"sort"
)
type Person struct {
Name string
Age int
}
func main() {
people := []Person{{"Zara", 25}, {"Amit", 30}, {"Bala", 22}}
sort.Slice(people, func(i, j int) bool {
return people[i].Age < people[j].Age
})
fmt.Println(people)
}
Login to try C/C++/Java/PHP code in the editor
Checking If a Slice Is Sorted
sort.IntsAreSorted (and its counterparts) check whether a slice is already in ascending order without modifying it, useful for validating assumptions before relying on binary search or similar.
Example: Checking If a Slice Is Sorted
package main
import (
"fmt"
"sort"
)
func main() {
nums := []int{1, 3, 5, 7}
fmt.Println("already sorted:", sort.IntsAreSorted(nums))
}
Login to try C/C++/Java/PHP code in the editor
- Calling sort.Sort with a slice directly instead of implementing sort.Interface, or forgetting sort.Slice's comparison function must return a strict less-than boolean.
- Assuming sort.Strings/Ints sort is stable -- for custom types needing stability, sort.SliceStable is required instead.
- Forgetting sort.Slice sorts the slice in place and returns nothing -- there's no return value to reassign.
- sort.Ints, sort.Strings, and sort.Float64s sort slices of those basic types in place.
- sort.Slice sorts any slice using a custom less-than comparison function.
- sort.SliceStable preserves the relative order of equal elements, unlike plain sort.Slice.
- sort.Search performs binary search on an already-sorted slice.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: