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
+18k Golang : Login and logout a user after password verification and redirect example
+19.9k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+6.1k Golang : Convert Chinese UTF8 characters to Pin Yin
+19.6k Golang : Example for DSA(Digital Signature Algorithm) package functions
+14.6k Golang : How to get URL port?
+5.8k Golang : Fix opencv.LoadHaarClassifierCascade The node does not represent a user object error
+12.3k Golang : Get remaining text such as id or filename after last segment in URL path
+20.7k Android Studio : AlertDialog and EditText to get user string input example
+10.1k Golang : Edge detection with Sobel method
+5k Golang : Constant and variable names in native language
+10.6k Golang : Flip coin example
+29.5k Golang : Saving(serializing) and reading file with GOB