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
+36.6k Golang : Validate IP address
+5.6k PHP : Convert CSV to JSON with YQL example
+16.5k Golang : File path independent of Operating System
+6.3k WARNING: UNPROTECTED PRIVATE KEY FILE! error message
+15.3k nginx: [emerg] unknown directive "ssl"
+46.5k Golang : Marshal and unmarshal json.RawMessage struct example
+16.3k Golang : convert string or integer to big.Int type
+13.1k Golang : Handle or parse date string with Z suffix(RFC3339) example
+6.6k Elasticsearch : Shutdown a local node
+8.4k Your page has meta tags in the body instead of the head
+19.2k Mac OSX : Homebrew and Golang