sort
6 methodsPackage 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
| Name | Type | Description |
|---|---|---|
| data | sort.Interface | Collection 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
| Name | Type | Description |
|---|---|---|
| x | any | Slice to sort. |
| less | func(i, j int) bool | Less 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
| Name | Type | Description |
|---|---|---|
| a | []string | Slice 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
| Name | Type | Description |
|---|---|---|
| a | []int | Slice 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
| Name | Type | Description |
|---|---|---|
| a | []float64 | Slice 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) intBinary search. Uses f to find the smallest index i in [0,n) at which f(i) is true.
Parameters
| Name | Type | Description |
|---|---|---|
| n | int | Length of the slice. |
| f | func(int) bool | Predicate. |
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