Skip to content

Instantly share code, notes, and snippets.

@schmohlio
Created September 7, 2016 21:37
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save schmohlio/615ab4d47bc01020786ef58aec622fdf to your computer and use it in GitHub Desktop.
Save schmohlio/615ab4d47bc01020786ef58aec622fdf to your computer and use it in GitHub Desktop.
sort byte slices in Golang without needing to fmt as string. useful for Set hashes
package main
import (
"bytes"
"log"
"sort"
)
// implement `Interface` in sort package.
type sortByteArrays [][]byte
func (b sortByteArrays) Len() int {
return len(b)
}
func (b sortByteArrays) Less(i, j int) bool {
// bytes package already implements Comparable for []byte.
switch bytes.Compare(b[i], b[j]) {
case -1:
return true
case 0, 1:
return false
default:
log.Panic("not fail-able with `bytes.Comparable` bounded [-1, 1].")
return false
}
}
func (b sortByteArrays) Swap(i, j int) {
b[j], b[i] = b[i], b[j]
}
// Public
func SortByteArrays(src [][]byte) [][]byte {
sorted := sortByteArrays(src)
sort.Sort(sorted)
return sorted
}
@xiegeo
Copy link

xiegeo commented Sep 12, 2019

Less could be shortened to:

func (b sortByteArrays) Less(i, j int) bool {
	return bytes.Compare(b[i], b[j]) < 0
}

@kduda
Copy link

kduda commented May 10, 2020

I think this entire code sample can be replaced with this:

func SortByteArrays(src [][]byte) {
	sort.Slice(src, func(i, j int) bool { return bytes.Compare(src[i], src[j]) < 0 })
}

(I think it's better to not return the sorted array, because it implies you didn't modify src, but of course you did --- src has been overwritten by the sorted array, in your implementation and in mine.)

-Ken

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment