Go by Example

Sorting

Sorting slices with slices.Sort (generic, Go 1.21+), slices.SortFunc for custom order, and sort.Search for binary search.

Sorting is a fundamental operation on collections. Go provides generic sorting via slices.Sort (Go 1.21+) for types with a natural order, slices.SortFunc for custom comparison logic, and sort.Search for binary search on already-sorted collections.

Sort a slice of integers in ascending order using slices.Sort. This is the generic, type-safe replacement for the older sort.Ints and sort.Slice functions.

package main
 
import (
    "fmt"
    "slices"
)
 
func main() {
    nums := []int{3, 1, 4, 1, 5, 9, 2, 6}
    slices.Sort(nums)
    fmt.Println(nums) // [1 1 2 3 4 5 6 9]
 
    // Sort in descending order using slices.SortFunc
    slices.SortFunc(nums, func(a, b int) int {
        return b - a // reverse comparison
    })
    fmt.Println(nums) // [9 6 5 4 3 2 1 1]
}

Sort strings - slices.Sort handles strings as well as any type with a natural order. Sort in reverse with slices.Reverse (Go 1.21+).

package main
 
import (
    "fmt"
    "slices"
)
 
func main() {
    words := []string{"zebra", "apple", "mango"}
    slices.Sort(words)
    fmt.Println(words) // [apple mango zebra]
 
    slices.Reverse(words)
    fmt.Println(words) // [zebra mango apple]
}

Binary search on a sorted slice with sort.Search or slices.BinarySearch. search.Search returns the index where the element would be inserted; slices.BinarySearch (Go 1.21+) returns the index and a bool indicating exact match.

package main
 
import (
    "fmt"
    "slices"
    "sort"
)
 
func main() {
    sorted := []int{1, 2, 3, 5, 8, 13}
 
    // slices.BinarySearch (Go 1.21+)
    idx, found := slices.BinarySearch(sorted, 5)
    fmt.Println(idx, found) // 3 true
 
    // sort.Search (returns insertion point)
    idx = sort.Search(len(sorted), func(i int) bool {
        return sorted[i] >= 8
    })
    fmt.Println(idx) // 4
}

In production

Prefer slices.Sort and slices.SortFunc (Go 1.21+) for new code - they are generic, type-safe, and measurably faster than sort.Slice. sort.Search is a stable binary search that works on any sorted collection; reach for it instead of linear scans in hot paths (log(n) vs n). Note that slices.Sort is not stable - equal elements may not retain their original order. Use slices.SortStableFunc if you need to preserve the original order of equal elements (e.g., sorting by priority then by creation time for display).

Enjoyed this? Get more essays on software craft delivered to your inbox.

Subscribe free