Sequence Sorting
Examples
Filter
Sometimes we’ll want to sort a collection by something other than its natural order. For example, suppose we wanted to sort strings by their length instead of alphabetically. Here’s an example of custom sorts in Go.
package main
import (
"fmt"
"sort"
)
type byLength []string
// We implement sort.Interface - Len, Less, and Swap -
// on our type so we can use the sort package’s generic Sort function.
// Len and Swap will usually be similar across types and
// Less will hold the actual custom sorting logic.
// In our case we want to sort in order of increasing string length,
// so we use len(s[i]) and len(s[j]) here.
func (s byLength) Len() int {
return len(s)
}
func (s byLength) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s byLength) Less(i, j int) bool {
return len(s[i]) < len(s[j])
}
// With all of this in place, we can now implement our custom sort by converting
// the original fruits slice to byLength, and then use sort.Sort on that typed slice.
func main() {
fruits := []string{"peach", "banana", "kiwi"}
sort.Sort(byLength(fruits))
fmt.Println(fruits)
}
Go’s sort package implements sorting for builtins and user-defined types.
package main
import (
"fmt"
"sort"
)
func main() {
// Sort methods are specific to the builtin type; here’s an example for strings.
// Note that sorting is in-place, so it changes the given slice and doesn’t return a new one.
strs := []string{"c", "a", "b"}
sort.Strings(strs)
fmt.Println("Strings:", strs)
// Sorting ints.
ints := []int{7, 2, 4}
sort.Ints(ints)
fmt.Println("Ints: ", ints)
// We can also use sort to check if a slice is already in sorted order.
s := sort.IntsAreSorted(ints)
fmt.Println("Sorted: ", s)
}