I'm trying to sort the characters in a string by sorting a slice of the bytes in the string (using sort.Slice). The code I'm using gets the right results sometimes but other times produces results I can't make sense of.
package main
import (
"fmt"
"sort"
)
func main() {
for _, s := range []string{"nat", "tan", "ant"} {
b := []byte(s)
sort.Slice(b, func(i int, j int) bool { return s[i] < s[j] })
fmt.Println(s, string(b))
}
}
https://play.golang.org/p/bC9QWq7aF3G
I would expect "nat", "tan" and "ant" to all be sorted to "ant", but "tan" is sorted to "atn".
Change your sort.Slice
line to:
sort.Slice(b, func(i int, j int) bool { return b[i] < b[j] })
sort.Slice
needs your less
function to compare values in the slice in order to sort the way you intended. Your bug is that you used s
rather than b
in your less
function.