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.2k Golang : Fix fmt.Scanf() on Windows will scan input twice problem
+7k Golang : Squaring elements in array
+6.7k Swift : substringWithRange() function example
+10.7k Golang : Command line file upload program to server example
+15.8k Golang : Read a file line by line
+10.7k PHP : Convert(cast) bigInt to string
+8.4k Golang : Add text to image and get OpenCV's X, Y co-ordinates example
+11k CodeIgniter : How to check if a session exist in PHP?
+9.1k Golang : Generate random Chinese, Japanese, Korean and other runes
+9.3k Golang : Find the length of big.Int variable example
+12k Golang : md5 hash of a string
+8.7k Golang : HTTP Routing with Goji example