Sorting
suggest changeGo has two packages for sorting:
slices(Go 1.21+) has generic functions:slices.Sort,slices.SortFunc,slices.SortStableFunc,slices.BinarySearchand friends. This is what you should use in new code.sortis the original package, from before Go had generics. It's still useful for sorting data that isn't a single slice, and you'll see it in a lot of existing code.
All sort functions sort in place. They don't return a new slice.
Sorting slices of basic types
slices.Sort sorts a slice of any ordered type: integers, floats, strings and named types based on them (anything satisfying cmp.Ordered):
package main
import (
"fmt"
"math"
"slices"
)
func main() {
nums := []int{5, 2, 8, 1, 9, 3}
slices.Sort(nums)
fmt.Println(nums)
words := []string{"pear", "Apple", "banana", "apple", "Cherry"}
slices.Sort(words)
fmt.Println(words)
floats := []float64{2.5, math.NaN(), -1, math.Inf(1), 0}
slices.Sort(floats)
fmt.Println(floats)
fmt.Println(slices.IsSorted(nums), slices.IsSorted([]int{1, 3, 2}))
// descending: sort, then reverse
slices.Reverse(nums)
fmt.Println(nums)
}
[1 2 3 5 8 9]
[Apple Cherry apple banana pear]
[NaN -1 0 2.5 +Inf]
true false
[9 8 5 3 2 1]
Things to notice:
- strings are compared byte by byte, so all upper case ASCII letters come before lower case letters. For alphabetical order as people expect it, see Sorting strings for humans in the localization article.
NaNsorts before every other float. With a plain<comparisonNaNwould break sorting, becauseNaN < xandx < NaNare both false.slices.IsSortedchecks if a slice is sorted in ascending order.- there is no "sort descending" function. Sort and then call
slices.Reverse, or useslices.SortFuncwith a reversed comparison, as shown below.
Custom order with slices.SortFunc
slices.SortFunc takes a comparison function func(a, b T) int that returns:
- a negative number if
ashould come beforeb - a positive number if
ashould come afterb - zero if they are equal for the purpose of sorting
cmp.Compare returns exactly that for any ordered type, and strings.Compare does the same for strings:
package main
import (
"cmp"
"fmt"
"slices"
"strings"
)
type Person struct {
Name string
Age int
}
func main() {
people := []Person{
{"Alice", 30},
{"bob", 25},
{"Carol", 35},
{"dave", 25},
{"Eve", 30},
}
// by age, ascending
slices.SortFunc(people, func(a, b Person) int {
return cmp.Compare(a.Age, b.Age)
})
fmt.Println(people)
// by age, descending: swap the arguments
slices.SortFunc(people, func(a, b Person) int {
return cmp.Compare(b.Age, a.Age)
})
fmt.Println(people)
// by name, case-insensitive
slices.SortFunc(people, func(a, b Person) int {
return strings.Compare(strings.ToLower(a.Name), strings.ToLower(b.Name))
})
fmt.Println(people)
// by age ascending, then by name
slices.SortFunc(people, func(a, b Person) int {
return cmp.Or(
cmp.Compare(a.Age, b.Age),
strings.Compare(a.Name, b.Name),
)
})
fmt.Println(people)
}
[{bob 25} {dave 25} {Alice 30} {Eve 30} {Carol 35}]
[{Carol 35} {Alice 30} {Eve 30} {bob 25} {dave 25}]
[{Alice 30} {bob 25} {Carol 35} {dave 25} {Eve 30}]
[{bob 25} {dave 25} {Alice 30} {Eve 30} {Carol 35}]
Patterns to remember:
- descending order: swap the arguments,
cmp.Compare(b.Age, a.Age) - multiple keys:
cmp.Orreturns its first non-zero argument. If ages differ that result wins; if they're equal, the name decides. Add more keys by adding more arguments. - case-insensitive: compare transformed values. Note that this calls
strings.ToLower(which allocates) on every comparison. The Performance section below shows a faster way.
Stable sorting
slices.Sort and slices.SortFunc use pattern-defeating quicksort, which is fast but not stable: elements that compare equal can end up in any order.
slices.SortStableFunc keeps equal elements in their original order. It matters when the slice is already ordered by something you want to preserve:
package main
import (
"cmp"
"fmt"
"slices"
)
type Order struct {
ID int
Customer string
}
func aliceIDs(orders []Order) []int {
var ids []int
for _, o := range orders {
if o.Customer == "alice" {
ids = append(ids, o.ID)
}
}
return ids
}
func main() {
customers := []string{"carol", "alice", "bob"}
var orders []Order // already ordered by ID
for id := 1; id <= 30; id++ {
orders = append(orders, Order{id, customers[id%3]})
}
byCustomer := func(a, b Order) int {
return cmp.Compare(a.Customer, b.Customer)
}
stable := slices.Clone(orders)
slices.SortStableFunc(stable, byCustomer)
fmt.Println("stable: ", aliceIDs(stable))
unstable := slices.Clone(orders)
slices.SortFunc(unstable, byCustomer)
fmt.Println("unstable:", aliceIDs(unstable))
}
stable: [1 4 7 10 13 16 19 22 25 28]
unstable: [13 28 25 4 22 19 7 1 16 10]
Orders were created sorted by ID. After a stable sort by customer, each customer's orders are still sorted by ID. After an unstable sort, they are scrambled.
For small slices (12 elements or less) the unstable sort uses insertion sort, which happens to be stable. Don't rely on that: test with bigger inputs, or use SortStableFunc when the order of equal elements matters.
An alternative to stable sorting is to make the comparison total by adding a tie-breaker key, e.g. cmp.Or(cmp.Compare(a.Customer, b.Customer), cmp.Compare(a.ID, b.ID)). This works with the faster unstable sort.
Sorting by time
time.Time must not be compared with <. Use its Compare method, which returns -1, 0 or +1, just like cmp.Compare:
package main
import (
"fmt"
"slices"
"time"
)
type Event struct {
Name string
At time.Time
}
func main() {
day := time.Date(2026, 10, 17, 0, 0, 0, 0, time.UTC)
events := []Event{
{"deploy", day.Add(15 * time.Hour)},
{"standup", day.Add(9*time.Hour + 30*time.Minute)},
{"lunch", day.Add(12 * time.Hour)},
{"backup", day.Add(2 * time.Hour)},
}
slices.SortFunc(events, func(a, b Event) int {
return a.At.Compare(b.At)
})
for _, e := range events {
fmt.Println(e.At.Format("15:04"), e.Name)
}
}
02:00 backup
09:30 standup
12:00 lunch
15:00 deploy
See Compare time and date for more about comparing times.
Sorting map keys
Iteration order of a map is random. To get deterministic output, sort the keys.
maps.Keys returns an iterator and slices.Sorted collects an iterator into a new, sorted slice. slices.SortedFunc does the same with a custom comparison function:
package main
import (
"cmp"
"fmt"
"maps"
"slices"
)
func main() {
stock := map[string]int{
"apples": 12,
"pears": 3,
"bananas": 25,
"kiwis": 3,
"plums": 8,
}
// keys in sorted order
for _, k := range slices.Sorted(maps.Keys(stock)) {
fmt.Printf("%-8s %2d\n", k, stock[k])
}
fmt.Println()
// keys ordered by value, descending; ties broken by key
keys := slices.SortedFunc(maps.Keys(stock), func(a, b string) int {
return cmp.Or(
cmp.Compare(stock[b], stock[a]),
cmp.Compare(a, b),
)
})
for _, k := range keys {
fmt.Printf("%-8s %2d\n", k, stock[k])
}
}
apples 12
bananas 25
kiwis 3
pears 3
plums 8
bananas 25
apples 12
plums 8
kiwis 3
pears 3
The second loop shows the common "sort map by value" pattern: you sort the keys, but the comparison function looks up and compares the values. A tie-breaker on the key makes the output deterministic when values are equal.
Binary search in sorted slices
Once a slice is sorted, you can find elements in O(log n) with slices.BinarySearch. It returns the position and whether the value was found. If the value is not there, the position is where it would be inserted to keep the slice sorted:
package main
import (
"cmp"
"fmt"
"slices"
)
type Product struct {
SKU string
Price int
}
func main() {
nums := []int{1, 3, 5, 7, 9, 11}
i, found := slices.BinarySearch(nums, 7)
fmt.Println(i, found)
// not found: i is where 6 would be inserted
i, found = slices.BinarySearch(nums, 6)
fmt.Println(i, found)
// keep the slice sorted while inserting
nums = slices.Insert(nums, i, 6)
fmt.Println(nums)
// search by key in a slice of structs sorted by SKU
products := []Product{{"A100", 250}, {"B200", 990}, {"C300", 120}}
j, ok := slices.BinarySearchFunc(products, "B200", func(p Product, sku string) int {
return cmp.Compare(p.SKU, sku)
})
fmt.Println(j, ok, products[j])
}
3 true
3 false
[1 3 5 6 7 9 11]
1 true {B200 990}
slices.BinarySearchFunc searches by a key of a different type than the slice elements. Here we search a slice of Product for a string SKU.
The slice must be sorted in the same order that the comparison function implies. Binary search on an unsorted slice, or one sorted by a different key, returns wrong results without any error.
Inserting with slices.Insert is O(n) because it shifts elements. For a lot of inserts and lookups consider a map or the heap from container/heap.
Other helpers for sorted data
Sorting is often a first step. Sorting groups equal values together, so slices.Compact, which removes consecutive duplicates, can remove all duplicates:
package main
import (
"fmt"
"slices"
)
func main() {
tags := []string{"go", "rust", "go", "zig", "c", "rust", "go"}
// sort, then remove adjacent duplicates
slices.Sort(tags)
tags = slices.Compact(tags)
fmt.Println(tags)
scores := []int{72, 95, 61, 88, 95}
fmt.Println(slices.Min(scores), slices.Max(scores))
// 3 highest scores without modifying the original
top := slices.Clone(scores)
slices.Sort(top)
slices.Reverse(top)
fmt.Println(top[:3], scores)
}
[c go rust zig]
61 95
[95 95 88] [72 95 61 88 95]
slices.Min and slices.Max find the smallest and largest element in O(n), without sorting. They panic on an empty slice.
Natural sort order
Sorting file names with slices.Sort puts file10.txt before file2.txt because '1' < '2'. A natural sort compares runs of digits as numbers. It's a good example of a non-trivial comparison function:
package main
import (
"cmp"
"fmt"
"slices"
"strings"
)
func isDigit(c byte) bool { return '0' <= c && c <= '9' }
// naturalCompare compares strings treating runs of digits as numbers,
// so "file2" sorts before "file10".
func naturalCompare(a, b string) int {
for a != "" && b != "" {
if isDigit(a[0]) && isDigit(b[0]) {
// split off the leading digit runs
i, j := 0, 0
for i < len(a) && isDigit(a[i]) {
i++
}
for j < len(b) && isDigit(b[j]) {
j++
}
na := strings.TrimLeft(a[:i], "0")
nb := strings.TrimLeft(b[:j], "0")
// a longer number (without leading zeros) is bigger
if c := cmp.Or(cmp.Compare(len(na), len(nb)), strings.Compare(na, nb)); c != 0 {
return c
}
a, b = a[i:], b[j:]
continue
}
if c := cmp.Compare(a[0], b[0]); c != 0 {
return c
}
a, b = a[1:], b[1:]
}
return cmp.Compare(len(a), len(b))
}
func main() {
files := []string{"file10.txt", "file2.txt", "file1.txt", "file20.txt", "file3.txt"}
slices.Sort(files)
fmt.Println(files)
slices.SortFunc(files, naturalCompare)
fmt.Println(files)
}
[file1.txt file10.txt file2.txt file20.txt file3.txt]
[file1.txt file2.txt file3.txt file10.txt file20.txt]
Comparing digit runs as strings, after stripping leading zeros and comparing lengths first, avoids parsing numbers and works for numbers of any size.
The sort package
Before Go 1.21 the sort package was the only option. You'll see it in existing code:
package main
import (
"fmt"
"sort"
)
type Person struct {
Name string
Age int
}
// ByAge implements sort.Interface.
type ByAge []Person
func (a ByAge) Len() int { return len(a) }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func main() {
nums := []int{5, 2, 8, 1}
sort.Ints(nums)
fmt.Println(nums, sort.IntsAreSorted(nums))
names := []string{"pear", "apple", "fig"}
sort.Strings(names)
fmt.Println(names)
people := []Person{{"Alice", 30}, {"Bob", 25}, {"Carol", 35}}
sort.Slice(people, func(i, j int) bool {
return people[i].Name > people[j].Name
})
fmt.Println(people)
sort.Sort(ByAge(people))
fmt.Println(people)
sort.Sort(sort.Reverse(ByAge(people)))
fmt.Println(people)
// sort.Search: smallest index for which f is true
i := sort.Search(len(nums), func(i int) bool { return nums[i] >= 6 })
fmt.Println(i)
}
[1 2 5 8] true
[apple fig pear]
[{Carol 35} {Bob 25} {Alice 30}]
[{Bob 25} {Alice 30} {Carol 35}]
[{Carol 35} {Alice 30} {Bob 25}]
3
sort.Ints,sort.Float64sandsort.Stringssort basic types. Since Go 1.22 they just callslices.Sort.sort.Sliceandsort.SliceStabletake a "less" function that receives indexes, not elements. The function must index the same slice that is being sorted, which is easy to get wrong.sort.Sortandsort.Stablesort any value implementingsort.Interface:Len,Less(i, j)andSwap(i, j).sort.Reversewraps asort.Interfaceand invertsLess.sort.Searchis a binary search that returns the smallest index for which the function returns true.
Converting from sort to slices:
| sort | slices |
|---|---|
sort.Ints(s), sort.Strings(s) |
slices.Sort(s) |
sort.Slice(s, func(i, j int) bool { return s[i].X < s[j].X }) |
slices.SortFunc(s, func(a, b T) int { return cmp.Compare(a.X, b.X) }) |
sort.SliceStable(...) |
slices.SortStableFunc(...) |
sort.IntsAreSorted(s) |
slices.IsSorted(s) |
sort.SearchInts(s, x) |
slices.BinarySearch(s, x) |
sort.Sort(sort.Reverse(sort.IntSlice(s))) |
slices.SortFunc(s, func(a, b int) int { return cmp.Compare(b, a) }) |
When sort.Interface is still useful
slices functions sort one slice. sort.Interface works with indexes, so it can sort anything that has a length and can swap two elements. For example, a table stored as parallel slices (columns), where each swap must move data in all of them:
package main
import (
"fmt"
"sort"
)
// columns stores a table as parallel slices.
type columns struct {
names []string
scores []int
}
func (c columns) Len() int { return len(c.names) }
func (c columns) Less(i, j int) bool { return c.scores[i] > c.scores[j] }
func (c columns) Swap(i, j int) {
c.names[i], c.names[j] = c.names[j], c.names[i]
c.scores[i], c.scores[j] = c.scores[j], c.scores[i]
}
func main() {
c := columns{
names: []string{"ann", "ben", "cid", "dot"},
scores: []int{70, 92, 85, 64},
}
sort.Stable(c)
fmt.Println(c.names)
fmt.Println(c.scores)
}
[ben cid ann dot]
[92 85 70 64]
Performance
Sorting is O(n log n) comparisons. The cost of each comparison matters a lot. A benchmark sorting 10,000 strings (each iteration also clones the slice):
func BenchmarkSortSlice(b *testing.B) {
for b.Loop() {
s := slices.Clone(names)
sort.Slice(s, func(i, j int) bool { return s[i] < s[j] })
}
}
func BenchmarkSlicesSort(b *testing.B) {
for b.Loop() {
s := slices.Clone(names)
slices.Sort(s)
}
}
func BenchmarkLowerInCompare(b *testing.B) {
for b.Loop() {
s := slices.Clone(names)
slices.SortFunc(s, func(a, b string) int {
return strings.Compare(strings.ToLower(a), strings.ToLower(b))
})
}
}
func BenchmarkLowerPrecomputed(b *testing.B) {
for b.Loop() {
type keyed struct{ key, val string }
ks := make([]keyed, len(names))
for i, n := range names {
ks[i] = keyed{strings.ToLower(n), n}
}
slices.SortFunc(ks, func(a, b keyed) int { return cmp.Compare(a.key, b.key) })
s := make([]string, len(ks))
for i, k := range ks {
s[i] = k.val
}
}
}
$ go test -bench . -benchmem
BenchmarkSortSlice-24 438 2702606 ns/op 163919 B/op 3 allocs/op
BenchmarkSlicesSort-24 595 2121765 ns/op 163840 B/op 1 allocs/op
BenchmarkLowerInCompare-24 74 21530372 ns/op 4622550 B/op 278669 allocs/op
BenchmarkLowerPrecomputed-24 331 3121347 ns/op 651521 B/op 10002 allocs/op
Takeaways:
slices.Sortis faster thansort.Slice: it compares with<directly and swaps elements without the reflection-based swapper thatsort.Sliceuses.- calling
strings.ToLowerinside the comparison function made sorting 10x slower: it runs about 2 * n * log n times and allocates every time. - computing the sort key once per element (the "decorate, sort, undecorate" pattern) brings it back close to a plain sort.
Common mistakes
package main
import (
"fmt"
"math"
"slices"
)
func main() {
// sorting a sub-slice sorts that part of the backing array
s := []int{9, 8, 7, 6, 5, 4}
slices.Sort(s[2:5])
fmt.Println(s)
// sort a copy to leave the original alone
orig := []int{3, 1, 2}
sorted := slices.Sorted(slices.Values(orig))
fmt.Println(orig, sorted)
// subtraction overflows for large values
nums := []int{math.MinInt, 1, math.MaxInt, 0}
slices.SortFunc(nums, func(a, b int) int { return a - b })
fmt.Println(nums)
}
[9 8 5 6 7 4]
[3 1 2] [1 2 3]
[0 1 9223372036854775807 -9223372036854775808]
- Sorting a sub-slice changes the original. A sub-slice shares its backing array with the slice it came from. Only positions 2 to 4 were sorted, in place. To sort without modifying the input, use
slices.Sorted(slices.Values(s))or sort aslices.Clone. - Subtraction in a comparison function.
a - blooks like a valid comparison, but overflows for large values and gives a wrong order. Always usecmp.Compare. - Inconsistent comparison. The comparison function must define a strict weak ordering: if
a < bandb < cthena < c, and the result must not change during the sort. A function that returns random results or comparesNaNfloats with<gives an unspecified order (it won't crash, but the result isn't sorted). For floats usecmp.Compare, which ordersNaNconsistently. - Forgetting that binary search needs sorted input, sorted by the same key and in the same direction as the search's comparison function.
Summary
- use
slices.Sortfor slices of numbers and strings,slices.SortFuncwithcmp.Comparefor everything else - swap arguments for descending order; combine keys with
cmp.Or - use
slices.SortStableFuncwhen the original order of equal elements matters - sort map keys with
slices.Sorted(maps.Keys(m)) - use
slices.BinarySearch/slices.BinarySearchFuncon sorted slices - the
sortpackage is legacy for slices, butsort.Interfacestill handles data that isn't a single slice - keep comparison functions cheap: precompute expensive keys