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.2k Golang : Convert source code to assembly language
+12.8k Golang : Handle or parse date string with Z suffix(RFC3339) example
+8.5k Golang : Executing and evaluating nested loop in html template
+14.6k Golang : Basic authentication with .htpasswd file
+19.2k Golang : How to Set or Add Header http.ResponseWriter?
+12.3k Golang : Add ASCII art to command line application launching process
+10.3k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+8.7k Golang : automatically figure out array length(size) with three dots
+5.4k Golang : Configure crontab to poll every two minutes 8am to 6pm Monday to Friday
+7.1k Golang : Calculate how many weeks left to go in a given year