To sort an array in Go, you can use the built-in sort package.
In this example,
numbers
with values 5, 2, 8, 1, 6.sort.Ints()
function from the sort package to sort the array in ascending order.sort.Ints()
function sorts the array elements in ascending order.numbers
to the console.package main
import (
"fmt"
"sort"
)
func main() {
numbers := []int{5, 2, 8, 1, 6}
sort.Ints(numbers)
fmt.Println("Sorted array in ascending order:", numbers)
}
Sorted array in ascending order: [1 2 5 6 8]
In this example,
numbers
with values 5, 2, 8, 1, 6.sort.Sort()
function with a custom sort.Interface implementation to sort the array in descending order.numbers
to the console.package main
import (
"fmt"
"sort"
)
type Descending []int
func (d Descending) Len() int { return len(d) }
func (d Descending) Less(i, j int) bool { return d[i] > d[j] }
func (d Descending) Swap(i, j int) { d[i], d[j] = d[j], d[i] }
func main() {
numbers := []int{5, 2, 8, 1, 6}
sort.Sort(Descending(numbers))
fmt.Println("Sorted array in descending order:", numbers)
}
Sorted array in descending order: [8 6 5 2 1]
In this tutorial, we learned How to Sort an Array in Go language with well detailed examples.