Go – Sort Slice of Integers
To sort a slice of integers in Go programming, use sort
package. sort
package offers sorting for builtin datatypes and user defined datatypes, through which we can sort a slice of integers.
The syntax to sort a slice of integers intSlice
using sort
package is
sort.Ints(intSlice)
The sorting happens in-place. Therefore original slice of integers is modified.
By default, the sorting happens in ascending order.
To sort in descending order, we may use sort.Reverse
function.
Note that we have to import sort
package prior to using sort.Ints
function.
Examples
In the following example, we will take a slice of integers in intSlice
, and sort them in ascending order using sort.Ints().
example.go
package main
import (
"fmt"
"sort"
)
func main() {
intSlice := []int{5, 3, 4, 1, 2}
fmt.Println("Before sorting :", intSlice)
sort.Ints(intSlice)
fmt.Println("After sorting :", intSlice)
}
Output
Before sorting : [5 3 4 1 2]
After sorting : [1 2 3 4 5]
Now, we shall sort this slice of integers in decreasing order, using sort.Reverse
function.
example.go
package main
import (
"fmt"
"sort"
)
func main() {
intSlice := []int{5, 3, 4, 1, 2}
fmt.Println("Before sorting :", intSlice)
sort.Sort(sort.Reverse(sort.IntSlice(intSlice)))
fmt.Println("After sorting :", intSlice)
}
Output
Before sorting : [5 3 4 1 2]
After sorting : [5 4 3 2 1]
Conclusion
In this Golang Tutorial, we learned how to sort a Slice of Integers in Go programming language using sort package, with the help of example programs.