garray_func.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2019 gf Author(https://github.com/gogf/gf). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package garray
  7. import "strings"
  8. // apiInterfaces is used for type assert api for Interfaces.
  9. type apiInterfaces interface {
  10. Interfaces() []interface{}
  11. }
  12. // defaultComparatorInt for int comparison.
  13. func defaultComparatorInt(a, b int) int {
  14. if a < b {
  15. return -1
  16. }
  17. if a > b {
  18. return 1
  19. }
  20. return 0
  21. }
  22. // defaultComparatorStr for string comparison.
  23. func defaultComparatorStr(a, b string) int {
  24. return strings.Compare(a, b)
  25. }
  26. // quickSortInt is the quick-sorting algorithm implements for int.
  27. func quickSortInt(values []int, comparator func(a, b int) int) {
  28. if len(values) <= 1 {
  29. return
  30. }
  31. mid, i := values[0], 1
  32. head, tail := 0, len(values)-1
  33. for head < tail {
  34. if comparator(values[i], mid) > 0 {
  35. values[i], values[tail] = values[tail], values[i]
  36. tail--
  37. } else {
  38. values[i], values[head] = values[head], values[i]
  39. head++
  40. i++
  41. }
  42. }
  43. values[head] = mid
  44. quickSortInt(values[:head], comparator)
  45. quickSortInt(values[head+1:], comparator)
  46. }
  47. // quickSortStr is the quick-sorting algorithm implements for string.
  48. func quickSortStr(values []string, comparator func(a, b string) int) {
  49. if len(values) <= 1 {
  50. return
  51. }
  52. mid, i := values[0], 1
  53. head, tail := 0, len(values)-1
  54. for head < tail {
  55. if comparator(values[i], mid) > 0 {
  56. values[i], values[tail] = values[tail], values[i]
  57. tail--
  58. } else {
  59. values[i], values[head] = values[head], values[i]
  60. head++
  61. i++
  62. }
  63. }
  64. values[head] = mid
  65. quickSortStr(values[:head], comparator)
  66. quickSortStr(values[head+1:], comparator)
  67. }