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
+8.5k Golang : Check if integer is power of four example
+5.2k Linux : How to set root password in Linux Mint
+14.6k Golang : How to shuffle elements in array or slice?
+11.7k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+7.8k Golang : Error reading timestamp with GORM or SQL driver
+15.4k JavaScript/JQuery : Detect or intercept enter key pressed example
+14.2k Golang : Google Drive API upload and rename example
+16.9k Golang : Generate QR codes for Google Authenticator App and fix "Cannot interpret QR code" error
+28.4k Golang : Connect to database (MySQL/MariaDB) server
+15.5k Golang : How to check if IP address is in range
+20.6k Golang : Check if os.Stdin input data is piped or from terminal
+11.1k Golang : Removes punctuation or defined delimiter from the user's input