Golang : Sort and reverse sort a slice of integers
Problem :
How to sort and reverse sort a slice of integers ?
Solution :
Use sort.Ints and sort.Sort functions.
package main
import (
"fmt"
"sort"
)
var intSlice = []int{4, 3, 2, 1, 0}
func main() {
fmt.Println("Original : ", intSlice[:])
sort.Ints(intSlice)
fmt.Println("Sort : ", intSlice)
sort.Sort(sort.Reverse(sort.IntSlice(intSlice)))
fmt.Println("Reverse Sort : ", intSlice)
}
Output :
Original : [4 3 2 1 0]
Sort : [0 1 2 3 4]
Reverse Sort : [4 3 2 1 0]
NOTE : There is a 3rd party package that can be used for sorting as well. See http://godoc.org/github.com/cznic/sortutil and https://www.socketloop.com/tutorials/golang-sort-and-reverse-sort-a-slice-of-bytes on how to use the sortutil
package
See also : Golang : Sort and reverse sort a slice of strings
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.9k Setting $GOPATH environment variable for Unix/Linux and Windows
+6.1k PHP : How to handle URI or URL with non-ASCII characters such as Chinese/Japanese/Korean(CJK) ?
+11.6k Golang : Find age or leap age from date of birth example
+9.2k Golang : How to get garbage collection data?
+4.6k Mac OSX : Get disk partitions' size, type and name
+16k Golang : How to check if input from os.Args is integer?
+20.1k Golang : Compare floating-point numbers
+11.3k Golang : Post data with url.Values{}
+22.3k Golang : Read directory content with filepath.Walk()
+9.8k Golang : Sort and reverse sort a slice of integers
+9.4k Golang : Detect Pascal, Kebab, Screaming Snake and Camel cases
+28.7k Golang : Detect (OS) Operating System