gobyexample/sorting/sorting.go

37 lines
605 B
Go
Raw Normal View History

2024-05-01 12:49:36 +00:00
package sorting
import (
"cmp"
"fmt"
"slices"
)
type Person struct {
name string
age uint
}
func Sorting() {
nums := []int{1, 3, 2, 5, 4}
slices.Sort(nums)
fmt.Printf("After sort: %v\n", nums)
fmt.Printf("Is nums sorted? %v\n", slices.IsSorted(nums))
slices.SortFunc(nums, func(a, b int) int {
return cmp.Compare(b, a)
})
fmt.Printf("After sorting with SortFunc: %v\n", nums)
peeps := []Person{
{"Jack", 30},
{"Depp", 32},
{"Markovich", 28},
}
slices.SortFunc(peeps, func(a, b Person) int {
return cmp.Compare(a.age, b.age)
})
fmt.Printf("Sorted by age: %v\n", peeps)
}