Sorting with the slices package
- Version
- 1.27
- Since
- 1.21
- Review
- Draft
Summary#
slices.Sort orders a slice of an ordered type in place. SortFunc uses a comparison function that returns a negative, zero or positive number. cmp.Or can chain comparisons for tie-breaking.
Syntax#
slices.Sort(values)
slices.SortFunc(items, func(a, b Item) int {
return cmp.Compare(a.Name, b.Name)
})
index, found := slices.BinarySearch(values, target)
Example#
package main
import (
"cmp"
"fmt"
"slices"
)
type player struct {
name string
score int
}
func main() {
ids := []int{30, 10, 20}
slices.Sort(ids)
fmt.Println(ids)
fmt.Println(slices.BinarySearch(ids, 20))
fmt.Println(slices.BinarySearch(ids, 25))
players := []player{{"mai", 90}, {"an", 75}, {"binh", 90}}
slices.SortFunc(players, func(a, b player) int {
return cmp.Or(
cmp.Compare(b.score, a.score), // higher score first
cmp.Compare(a.name, b.name),
)
})
fmt.Println(players)
}
Expected output#
[10 20 30]
1 true
2 false
[{binh 90} {mai 90} {an 75}]
Common mistakes#
Use SortStableFunc to keep equal elements in their original order. Give either sort a consistent ordering, and use cmp.Compare instead of subtracting integers, which can overflow. BinarySearch requires increasing order and returns the insertion index when the target is absent.
Version applicability#
Go 1.21 added the slices functions shown and cmp.Compare. The complete example requires Go 1.22 for cmp.Or. On Go 1.21, chain comparisons with if statements. Before Go 1.21, use the sort package.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0