How to sort a slice of ints in Golang?
Last Updated :
12 Jul, 2025
In Go, slices provide a flexible way to manage sequences of elements. To sort a slice of int
s, the sort
package offers a few straightforward functions. In this article we will learn How to Sort a Slice of Ints in Golang.
Example
Go
package main
import (
"fmt"
"sort"
)
func main() {
intSlice := []int{42, 23, 16, 15, 8, 4}
fmt.Println("Before:", intSlice)
// Sorting in ascending order
sort.Ints(intSlice)
fmt.Println("After:", intSlice)
}
OutputBefore: [42 23 16 15 8 4]
After: [4 8 15 16 23 42]
Syntax
func Ints(slc []int) #Sorting with sort.Ints
func IntsAreSorted(slc []int) bool # Check Slice sorting with sort.IntsAreSorted
Sorting with sort.Ints
The sort.Ints
function sorts a slice of int
s in ascending order, modifying the slice directly.
Syntax
func Ints(slc []int)
Example
Using the earlier intSlice
example, we applied sort.Ints
to sort the integers in place. The result is an ascending order.
Checking if a Slice is Sorted with sort.IntsAreSorted
If you need to check whether a slice is already sorted in ascending order, you can use sort.IntsAreSorted
. This function returns true
if the slice is sorted and false
otherwise.
Syntax
func IntsAreSorted(slc []int) bool
Example
Go
package main
import (
"fmt"
"sort"
)
func main() {
intSlice := []int{42, 23, 16, 15, 8, 4}
// Check if the slice is sorted
fmt.Println("sorted before sorting?:", sort.IntsAreSorted(intSlice))
// Sort the slice
sort.Ints(intSlice)
// Check again
fmt.Println("sorted after sorting?:", sort.IntsAreSorted(intSlice))
}
Outputsorted before sorting?: false
sorted after sorting?: true
Sorting in Descending Order with sort.Slice
If you want to sort in descending order, you can use sort.Slice
with a custom comparison function.
Example
Go
package main
import (
"fmt"
"sort"
)
func main() {
intSlice := []int{42, 23, 16, 15, 8, 4}
// Sort in descending order
sort.Slice(intSlice, func(i, j int) bool {
return intSlice[i] > intSlice[j]
})
fmt.Println("descending order:", intSlice)
}
Note: If you are encountering an error indicating that the sort.Slice
function is not recognized, it may be due to using an older version of Go that does not support this function. The sort.Slice
function was introduced in Go 1.8, so ensure that your Go version is at least 1.8 or higher.
Explore
Go Tutorial
3 min read
Overview
Fundamentals
Control Statements
Functions & Methods
Structure
Arrays
Slices
Strings
Pointers