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
+9k Golang : Capture text return from exec function example
+21k Golang : For loop continue,break and range
+6.8k Golang : Muxing with Martini example
+7.5k Golang : Dealing with struct's private part
+31.6k Golang : How to convert(cast) string to IP address?
+6.2k Golang & Javascript : How to save cropped image to file on server
+8.5k Golang : Add text to image and get OpenCV's X, Y co-ordinates example
+17.6k Golang : Read data from config file and assign to variables
+24.4k Golang : Change file read or write permission example
+8.7k Golang : On lambda, anonymous, inline functions and function literals
+17.1k Golang : Find file size(disk usage) with filepath.Walk
+9k Golang : Get curl -I or head data from URL example