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
+24.4k Golang : Detect (OS) Operating System
+9.4k Swift : Convert (cast) Float to String
+4.4k Golang : How to fix html/template : "somefile" is undefined error?
+3.3k Golang : Check if a word is countable or not
+21.6k Golang : GORM read from database example
+14.9k Golang : Convert(cast) bytes.Buffer or bytes.NewBuffer type to io.Reader
+6.5k nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
+2.2k Java : Random alphabets, alpha-numeric or numbers only string generator
+15.5k Golang : Padding data for encryption and un-padding data for decryption
+29.5k Golang : Validate IP address
+9.7k Golang : Skip blank/empty lines in CSV file and trim whitespaces example
+7k Golang : Inject/embed Javascript before sending out to browser example