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
+23.3k Golang : Randomly pick an item from a slice/array example
+22.3k Golang : Print leading(padding) zero or spaces in fmt.Printf?
+11.5k Golang : Delay or limit HTTP requests example
+6.8k Golang : When to use make or new?
+6k AWS S3 : Prevent Hotlinking policy
+9.6k Golang : Get all countries currencies code in JSON format
+5k HTTP common errors and their meaning explained
+23.7k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+10.1k Golang : Channels and buffered channels examples
+8.9k Golang : Take screen shot of browser with JQuery example
+9.5k Golang : How to get username from email address
+7.5k Golang : How to convert strange string to JSON with json.MarshalIndent