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
+11.7k Golang : http.Get example
+12.6k Golang : Fix image: unknown format error
+18.9k Nginx + FastCGI + Go Setup.
+5.5k Golang : Find the longest line of text example
+15.1k Golang : Check if a string contains multiple sub-strings in []string?
+9.5k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?
+31.6k Delete a directory in Go
+17.3k Golang : Get path name to current directory or folder
+14.8k Golang : Get sub string example
+5.1k Golang : Selection sort example
+20.4k Golang : Convert seconds to minutes and remainder seconds
+11.4k Golang : Exit, terminating or aborting a program