Add sorting
This commit is contained in:
36
sorting/sorting.go
Normal file
36
sorting/sorting.go
Normal file
@@ -0,0 +1,36 @@
|
||||
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)
|
||||
}
|
||||
Reference in New Issue
Block a user