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 840 B

1 year ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package sort2
  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]) []T {
  22. st := sorter[T]{
  23. arr: arr,
  24. cmp: cmp,
  25. }
  26. sort.Sort(st)
  27. return arr
  28. }
  29. // false < true
  30. func CmpBool(left, right bool) int {
  31. leftVal := 0
  32. if left {
  33. leftVal = 1
  34. }
  35. rightVal := 0
  36. if right {
  37. rightVal = 1
  38. }
  39. return leftVal - rightVal
  40. }
  41. func Cmp[T constraints.Ordered](left, right T) int {
  42. if left == right {
  43. return 0
  44. }
  45. if left < right {
  46. return -1
  47. }
  48. return 1
  49. }