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
+9.1k Golang : How to control fmt or log print format?
+6.7k Mac/Linux/Windows : Get CPU information from command line
+15.8k Golang : Read a file line by line
+7.7k Golang : Ways to recover memory during run time.
+18.6k Unmarshal/Load CSV record into struct in Go
+12.9k Golang : Calculate elapsed years or months since a date
+7.4k Golang : Rot13 and Rot5 algorithms example
+9.7k Golang : ffmpeg with os/exec.Command() returns non-zero status
+19.7k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+8.9k Golang : Get curl -I or head data from URL example
+7.4k Golang : Detect sample rate, channels or latency with PortAudio