43. Go - Sorts and Custom Sorts
Go built in sort functions can sort default slice variables and also custom ones.
Example: Ints and Strings
package main
import (
"fmt"
"sort"
)
func main() {
numbers := []int{5, 2, 8, 2, 52, 111}
words := []string{"hello", "die", "pink", "ablw"}
fmt.Println(numbers)
fmt.Println(words)
sort.Ints(numbers)
sort.Strings(words)
fmt.Println(numbers)
fmt.Println(words)
}
Custom Sort: requires giving the type of data we want to sort a list of similar methods of the built in sort functions so they can be of the same interface. https://pkg.go.dev/sort#example-package
Using sort.Sort(Custom(struct))
Example:
package main
import (
"fmt"
"sort"
)
type blob struct {
Size int
Name string
}
type bySize []blob
type byName []blob
func (a bySize) Len() int { return len(a) }
func (a bySize) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a bySize) Less(i, j int) bool { return a[i].Size < a[j].Size }
func (a byName) Len() int { return len(a) }
func (a byName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byName) Less(i, j int) bool { return a[i].Name < a[j].Name }
func main() {
blob1 := blob{5, "red"}
blob2 := blob{6, "blue"}
blob3 := blob{7, "orange"}
blob4 := blob{8, "white"}
blob5 := blob{9, "pink"}
blobs := []blob{blob1, blob2, blob3, blob4, blob5}
fmt.Println(blobs)
sort.Sort(bySize(blobs))
fmt.Println(blobs)
sort.Sort(byName(blobs))
fmt.Println(blobs)
}
Comments
Post a Comment