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
+4.2k Javascript : Empty an array example
+10.3k Golang : Detect number of faces or vehicles in a photo
+45.1k Golang : Use wildcard patterns with filepath.Glob() example
+15.3k Golang : Get timezone offset from date or timestamp
+8.3k Golang : Reverse text lines or flip line order example
+5.4k Golang : Intercept, inject and replay HTTP traffics from web server
+22.8k Golang : Round float to precision example
+9.5k Golang : Scramble and unscramble text message by randomly replacing words
+24.7k Golang : How to validate URL the right way
+6.4k Golang : Break string into a slice of characters example
+10.3k Golang : Wait and sync.WaitGroup example
+8.3k Golang : Find relative luminance or color brightness