Home > Article > Backend Development > How do I sort a slice of integers in reverse order in Go?
Sorting a Slice of Integers in Reverse Order in Go
In Go, sorting a slice of integers in ascending order is straightforward using the sort.Ints function. However, if you need to sort in reverse order, the process can be confusing.
To understand the issue, let's break it down into steps:
example := []int{1, 25, 3, 5, 4} sort.Ints(example) // [1, 3, 4, 5, 25]
sort.Sort(sort.Reverse(sort.Ints(keys)))
However, this approach results in an error because sort.Ints is a function that sorts the slice in-place, and it doesn't return a slice.
The solution is to use the sort.IntSlice type, which implements the sort.Interface interface for slices of integers. This allows us to sort the slice using the Reverse method:
keys := []int{3, 2, 8, 1} sort.Sort(sort.Reverse(sort.IntSlice(keys))) fmt.Println(keys) // [8, 3, 2, 1]
In this example, keys is sorted from highest to lowest using the sort.Reverse method.
The above is the detailed content of How do I sort a slice of integers in reverse order in Go?. For more information, please follow other related articles on the PHP Chinese website!