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
+8.6k Golang : Populate slice with sequential integers example
+35k Golang : Display float in 2 decimal points and rounding up or down
+13.6k Golang : Adding XML attributes to xml data or use attribute to differentiate a common tag name
+37.6k Golang : How to read CSV file
+9.4k Golang : Flip coin example
+16.8k Golang : Check if a directory exist or not
+25k Golang : Convert file content into array of bytes
+6.1k Web : How to see your website from different countries?
+6.7k Golang : Reverse a string with unicode
+4.6k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example
+19.6k Golang : How to read float value from standard input ?
+3.9k Javascript : How to get width and height of a div?