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
+6.3k Golang : How to stop user from directly running an executable file?
+4.3k Javascript : Change page title to get viewer attention
+5.8k Fix sudo yum hang problem with no output or error messages
+7.9k Golang : How to use Gorilla webtoolkit context package properly
+12.9k Golang : syscall.Socket example
+3.6k Adding Skype actions such as call and chat into web page examples
+7.2k Your page has meta tags in the body instead of the head
+3.6k Javascript : Access JSON data example
+32.9k Golang : Integer is between a range
+25.1k Golang : Calculate future date with time.Add() function
+4k Fix Google Analytics Redundant Hostnames problem