Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 147 ยท Collections

Sorting

Learn to sort in Go - sort.Ints and sort.Slice, slices.SortFunc with cmp, multi-key sorting, stable sorts, the sort.Interface, reverse order, sorting maps by value and binary search with sort.Search.

Sorting is one of those jobs every program does: leaderboards, alphabetical lists, "newest first" feeds, reports ordered by price. Go gives you two families of tools. The older sort package has been there since Go 1.0. The newer slices package (Go 1.21) has generic sorting functions that are shorter, type-safe and a little faster. Both are in the standard library, and you'll meet both in real code.

This lesson starts with the quick one-liners, then covers custom orders, multi-key sorting, stability, the sort.Interface, sorting a map by its values and searching sorted data. If you have only 30 seconds: use slices.Sort for numbers and strings, and slices.SortFunc with cmp.Compare for everything else.

Sorting numbers and strings

For slices of numbers or strings, the shortest call is slices.Sort. The classic sort.Ints, sort.Strings and sort.Float64s do the same thing for those three types:

Go Sorting basic slices

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Strings compare byte by byte in UTF-8, so "Apple" sorts before "apple" and both sort before "banana". Natural-language ordering (accents, locale rules) isn't part of the standard library; see Unicode and Text Processing for pointers.

Both families sort in place. They don't return a new slice, so make a copy first with slices.Clone if you need the original order too.

Sorting structs with a custom comparison

For structs, tell the sort how to compare two elements. With slices.SortFunc you write a function that takes two elements and returns a negative number if the first comes first, zero if they tie, and a positive number otherwise. cmp.Compare does exactly that for ordered types:

Go slices.SortFunc

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The older sort.Slice takes a different kind of function: less(i, j int) bool, working with indexes into the slice. It accepts any slice (through any, with reflection under the hood), so it isn't type-checked and is a bit slower:

Go sort.Slice with a less function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Prefer slices.SortFunc in new code, but you'll see sort.Slice everywhere in older codebases, so you need to read both.

A comparison function must be consistent: if a sorts before b, then b must not sort before a, and it must treat equal items as equal. A broken function (for example <= in a less function) can produce wrong results, and the sort never reports an error.

Sorting by several keys

Real data needs tie-breakers: sort by score, then by name. In a SortFunc, compare the first key, and when it returns 0, compare the next. cmp.Or returns the first non-zero value, so it chains the keys neatly:

Go Multi-key sorting with cmp.Or

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Before Go 1.22 you would write the same thing as a chain of if a.X != b.X { return ... } statements; that still works and is sometimes clearer for long chains.

Stable sorting

A stable sort keeps items that compare equal in their original relative order. That matters when you sort a list by one key after sorting by another (sort by name, then stable-sort by department: names stay alphabetical inside each department). The plain sorts make no such promise; they are free to reorder ties. Use the stable versions when ties exist and the order matters: slices.SortStableFunc or sort.SliceStable.

Go Stable sorts keep ties in order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Within each priority, the titles stay in the order they were in the input: test, plan, ship for priority 1, and write, deploy, fix for priority 2. With an unstable sort, that order could change. The standard sort.Sort and slices.Sort use pattern-defeating quicksort, which is fast but unstable.

Reverse order

To sort descending you can swap the arguments of the comparison, as above, or sort ascending and call slices.Reverse. With the older package, wrap a sort.Interface in sort.Reverse:

Go Descending order three ways

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The sort.Interface

Before generics, sorting was driven by an interface with three methods. Any type that implements it works with sort.Sort and sort.Stable:

Go
type Interface interface {
	Len() int
	Less(i, j int) bool
	Swap(i, j int)
}

Defining a named slice type with these methods lets you reuse the same ordering in many places, and it is the right tool for data structures that aren't slices:

Go Implementing sort.Interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Notice that sort.Sort(ByTemp(readings)) converts the plain slice to the named type; no data is copied. This is a nice example of custom types carrying behavior.

Sorting a map by its values

Maps have no order, so "sort a map" really means "extract the entries into a slice and sort that". Make a slice of key-value structs, or just sort the keys with a comparison that looks values up:

Go Top words by count

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The tie-breaker on the word makes the output deterministic. Without it, words with equal counts would come out in whichever order the random map iteration produced.

On sorted data, searching by halves takes about log2(n) steps instead of n. slices.BinarySearch (for ordered types) and slices.BinarySearchFunc (for custom comparisons) return the position and whether the value was found. The lower-level sort.Search(n, f) finds the smallest index where f(i) is true, and f must be false and then true across the range:

Go sort.Search and slices.BinarySearch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The insertion position is the key to keeping a slice sorted as you add to it: pos, _ := slices.BinarySearch(s, x); s = slices.Insert(s, pos, x).

Binary search on an unsorted slice returns garbage and no error. Sort first, or know that the data is already ordered.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which call sorts []string alphabetically in place?

    slices.Sort sorts in place and returns nothing. slices.Sorted takes an iterator, not a slice, and sort.Strings also returns nothing.
  2. 2. What must a slices.SortFunc comparison return when the first item should come before the second?

    The function returns a negative number, zero or a positive number. cmp.Compare(a, b) is negative when a < b.
  3. 3. When do you need SortStableFunc instead of SortFunc?

    Only the stable sorts guarantee that tied elements keep their relative order.
  4. 4. How do you get the words of a map sorted by count, highest first?

    Maps have no order. Put the keys in a slice, then sort that slice using the map's values.
  5. 5. What does sort.Search(n, f) require of f?

    sort.Search does a binary search for the smallest index where f is true, so f must flip from false to true exactly once.

Summary

  • slices.Sort sorts numbers and strings in place; sort.Ints, sort.Strings and sort.Float64s are the older equivalents.
  • Use slices.SortFunc(s, func(a, b T) int) with cmp.Compare for custom orders; swap the arguments for descending order.
  • sort.Slice(s, func(i, j int) bool) still appears in older code but is not type-checked.
  • Chain keys with cmp.Or(cmp.Compare(...), cmp.Compare(...)) for multi-key sorting.
  • Plain sorts are not stable. Use slices.SortStableFunc or sort.SliceStable when ties must keep their order.
  • sort.Interface (Len, Less, Swap) plus sort.Reverse is the pre-generics way to define reusable orderings.
  • To sort a map, sort a slice of its keys or entries and add a tie-breaker for a deterministic result.
  • Binary search (slices.BinarySearch, sort.Search) needs sorted data.

Next: Working with Strings: strings, strconv and unicode moves from sorting lists to slicing, searching and converting text.