Sort with sort and slices
Sort with sort and slices
The standard library provides sort for index-based sorting and slices for typed slice operations. slices.Sort sorts ordered elements in place; slices.SortFunc accepts a comparator returning a negative, zero or positive integer. Choose a stable sort when equal-key records must keep their original relative order.
package main
import ( "fmt" "slices")
func main() { a := []int{4, 1, 3, 1} slices.Sort(a) fmt.Println(a) i, ok := slices.BinarySearch(a, 3) fmt.Println(i, ok) i, ok = slices.BinarySearch(a, 2) fmt.Println(i, ok)}BinarySearch requires ascending sorted input. It returns the earliest matching index, or the insertion index if the key is absent. Sort mutates the original backing array; clone first if callers need the original order. The slices package was added in Go 1.21.
Expected output:
[1 1 3 4]2 true2 falsePreserve equal-key order
package main
import ( "cmp" "fmt" "slices" "sort")
type Job struct { Name string Priority int}
func main() { a := []Job{{"A", 2}, {"B", 1}, {"C", 2}} b := slices.Clone(a) slices.SortStableFunc(a, func(x, y Job) int { return cmp.Compare(x.Priority, y.Priority) }) sort.SliceStable(b, func(i, j int) bool { return b[i].Priority < b[j].Priority }) fmt.Println(a) fmt.Println(b)}Both stable sorts preserve A before C. SortStableFunc compares values, while sort.SliceStable uses indices into the slice. A comparator must define a strict weak ordering (consistent ordering and equivalence classes); avoid <= in a less function, subtracting potentially overflowing integers, or changing data inside a comparator.
Expected output:
[{B 1} {A 2} {C 2}][{B 1} {A 2} {C 2}]Try it locally
Sort a clone of []int{8,2,5} descending with slices.SortFunc and cmp.Compare; print the original and sorted copy.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Core library 04: Sort with sort and slices
Check the lesson objective before moving on.
What does a stable sort preserve?
What is required before slices.BinarySearch on integers?