![]() |
VOOZH | about |
In Go, slices provide a flexible way to manage sequences of elements. To sort a slice of ints, the sort package offers a few straightforward functions. In this article we will learn How to Sort a Slice of Ints in Golang.
Example
Before: [42 23 16 15 8 4] After: [4 8 15 16 23 42]
func Ints(slc []int) #Sorting with sort.Ints
func IntsAreSorted(slc []int) bool # Check Slice sorting with sort.IntsAreSorted
Table of Content
sort.IntsThe sort.Ints function sorts a slice of ints in ascending order, modifying the slice directly.
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.
sort.IntsAreSortedIf 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.
func IntsAreSorted(slc []int) boolExample
sorted before sorting?: false sorted after sorting?: true
sort.SliceIf you want to sort in descending order, you can use sort.Slice with a custom comparison function.
Example
Note: If you are encountering an error indicating that the
sort.Slicefunction is not recognized, it may be due to using an older version of Go that does not support this function. Thesort.Slicefunction was introduced in Go 1.8, so ensure that your Go version is at least 1.8 or higher.