You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

sort.go 807 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package sort
  2. import (
  3. "sort"
  4. "golang.org/x/exp/constraints"
  5. )
  6. type Comparer[T any] func(left T, right T) int
  7. type sorter[T any] struct {
  8. arr []T
  9. cmp Comparer[T]
  10. }
  11. func (s sorter[T]) Len() int {
  12. return len(s.arr)
  13. }
  14. func (s sorter[T]) Less(i int, j int) bool {
  15. ret := s.cmp(s.arr[i], s.arr[j])
  16. return ret < 0
  17. }
  18. func (s sorter[T]) Swap(i int, j int) {
  19. s.arr[i], s.arr[j] = s.arr[j], s.arr[i]
  20. }
  21. func Sort[T any](arr []T, cmp Comparer[T]) {
  22. st := sorter[T]{
  23. arr: arr,
  24. cmp: cmp,
  25. }
  26. sort.Sort(st)
  27. }
  28. func CmpBool(left, right bool) int {
  29. leftVal := 0
  30. if left {
  31. leftVal = 1
  32. }
  33. rightVal := 0
  34. if right {
  35. rightVal = 1
  36. }
  37. return leftVal - rightVal
  38. }
  39. func Cmp[T constraints.Ordered](left, right T) int {
  40. if left == right {
  41. return 0
  42. }
  43. if left < right {
  44. return -1
  45. }
  46. return 1
  47. }

公共库

Contributors (1)