Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Collections: sort, slices, maps

Go sort.Ints(), Strings() and Float64s() functions

Reference for Go sort.Ints, sort.Strings and sort.Float64s: sort a slice in place in increasing order, check it with the AreSorted functions, NaN handling.

sort.Ints, sort.Strings and sort.Float64s sort a slice of int, string or float64 in increasing order, in place. They return nothing: the slice you pass is the one that changes. Each has a companion that reports whether a slice is already sorted: IntsAreSorted, StringsAreSorted and Float64sAreSorted.

Strings compare byte by byte, so uppercase letters come before lowercase ones and non-ASCII text sorts by its UTF-8 bytes, not by language rules.

Go
names := []string{"bob", "Ann", "cy"}
sort.Strings(names) // [Ann bob cy]

Try it

Go Sorting the three basic types

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.

Go Sorting a copy and sorting descending

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.

Syntax

Go
func Ints(x []int)
func Strings(x []string)
func Float64s(x []float64)
func IntsAreSorted(x []int) bool
func StringsAreSorted(x []string) bool
func Float64sAreSorted(x []float64) bool
Name Description
x The slice to sort or check. A nil or empty slice is fine.

Returns: the Sort functions return nothing; the AreSorted functions return true when x is in non-decreasing order.

Edge cases: NaN values in Float64s are ordered before all other numbers. Passing a nil slice does nothing and does not panic.

Usage notes

  • In place, no return value. Writing x = sort.Ints(x) does not compile. If you must keep the original order, clone first.
  • Not stable is irrelevant for these types, because equal ints, strings or floats are indistinguishable.
  • Byte order for strings. "Z" sorts before "a", and "10" before "9". For case-insensitive or numeric ("natural") ordering use sort.Slice or slices.SortFunc with your own comparison, for example strings.ToLower or strings.Compare on a normalized key. Language-aware collation needs golang.org/x/text/collate, which is not in the standard library.
  • Time complexity is O(n log n). A sorted input is detected quickly, so sorting twice is cheap.
  • Other element types (int64, uint8, named types) are not covered. Use sort.Slice, or the generic slices.Sort, which accepts any ordered type.
  • Since Go 1.22 these functions simply call slices.Sort, so their speed is the same as the generic version.