Golang : Sort and reverse sort a slice of bytes
Problem :
How to sort and reverse sort a slice of bytes ?
Solution :
Import "github.com/cznic/sortutil"
Use the ByteSlice type ( see http://godoc.org/github.com/cznic/sortutil#ByteSlice ) and invoke the Sort() method.
package main
import (
"fmt"
"github.com/cznic/sortutil"
"sort"
)
var bytes sortutil.ByteSlice = []byte("zxvfbac")
func main() {
// Bytes
fmt.Println("Original : ", string(bytes[:]))
fmt.Println("Original : ", bytes[:])
sort.Sort(bytes)
fmt.Println("Sort : ", string(bytes[:]))
fmt.Println("Sort : ", bytes[:])
sort.Sort(sort.Reverse(bytes[:]))
fmt.Println("Reverse : ", string(bytes[:]))
fmt.Println("Reverse : ", bytes[:])
}
Output :
Original : zxvfbac
Original : [122 120 118 102 98 97 99]
Sort : abcfvxz
Sort : [97 98 99 102 118 120 122]
Reverse : zxvfcba
Reverse : [122 120 118 102 99 98 97]
See also : Golang : Sort and reverse sort a slice of runes
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
+2.5k Golang : Compound interest over time example
+4.3k Golang : Generate random elements without repetition or duplicate
+2.2k Golang : Calculate BMI and risk category
+52k Golang : Convert HTTP Response body to string
+20k Golang : Move file to another directory
+1.9k Javascript : Empty an array example
+5k Golang : Get month name from date example
+5.6k Golang : Get current, epoch time and display by year, month and day
+7k Golang : Search folders for file recursively with wildcard support
+1.5k Golang : Gargish-English language translator
+9.3k nginx: [emerg] unknown directive "ssl"
+18.7k Golang : How do I convert int to uint8?