Skip to content

Go sort API

Go sort package — sorting slices and custom collections.

1 class · 6 methods

sort

6 methods

Package sort provides primitives for sorting slices and user-defined collections.

sort.Sort(data sort.Interface)

Sort data in place. data must implement sort.Interface (Len, Less, Swap).

Parameters

NameTypeDescription
datasort.InterfaceCollection to sort.

Returns

void

Example

go
type ByLen []string
func (a ByLen) Len() int           { return len(a) }
func (a ByLen) Less(i,j int) bool  { return len(a[i]) < len(a[j]) }
func (a ByLen) Swap(i,j int)       { a[i], a[j] = a[j], a[i] }

sort.Sort(ByLen{"bb", "a", "ccc"})
// ["a", "bb", "ccc"]
sort.Slice(x any, less func(i, j int) bool)

Sort x in place using a less function. Convenience wrapper avoiding sort.Interface.

Parameters

NameTypeDescription
xanySlice to sort.
lessfunc(i, j int) boolLess comparator.

Returns

void

Example

go
s := []string{"bb", "a", "ccc"}
sort.Slice(s, func(i, j int) bool {
    return len(s[i]) < len(s[j])
})
// s == ["a", "bb", "ccc"]
sort.Strings(a []string)

Sort a slice of strings in increasing order in place.

Parameters

NameTypeDescription
a[]stringSlice to sort.

Returns

void

Example

go
s := []string{"c", "a", "b"}
sort.Strings(s)
// s == ["a", "b", "c"]
sort.Ints(a []int)

Sort a slice of ints in increasing order in place.

Parameters

NameTypeDescription
a[]intSlice to sort.

Returns

void

Example

go
n := []int{3, 1, 2}
sort.Ints(n)
// n == [1, 2, 3]
sort.Float64s(a []float64)

Sort a slice of float64s in increasing order in place.

Parameters

NameTypeDescription
a[]float64Slice to sort.

Returns

void

Example

go
f := []float64{3.1, 1.2, 2.5}
sort.Float64s(f)
// f == [1.2, 2.5, 3.1]
sort.Search(n int, f func(int) bool) int

Binary search. Uses f to find the smallest index i in [0,n) at which f(i) is true.

Parameters

NameTypeDescription
nintLength of the slice.
ffunc(int) boolPredicate.

Returns

int

Example

go
a := []int{1, 3, 5, 7, 9}
i := sort.Search(len(a), func(i int) bool { return a[i] >= 5 })
// i == 2, a[i] == 5