garray_func.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright GoFrame Author(https://goframe.org). 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. // defaultComparatorInt for int comparison.
  9. func defaultComparatorInt(a, b int) int {
  10. if a < b {
  11. return -1
  12. }
  13. if a > b {
  14. return 1
  15. }
  16. return 0
  17. }
  18. // defaultComparatorStr for string comparison.
  19. func defaultComparatorStr(a, b string) int {
  20. return strings.Compare(a, b)
  21. }
  22. // quickSortInt is the quick-sorting algorithm implements for int.
  23. func quickSortInt(values []int, comparator func(a, b int) int) {
  24. if len(values) <= 1 {
  25. return
  26. }
  27. mid, i := values[0], 1
  28. head, tail := 0, len(values)-1
  29. for head < tail {
  30. if comparator(values[i], mid) > 0 {
  31. values[i], values[tail] = values[tail], values[i]
  32. tail--
  33. } else {
  34. values[i], values[head] = values[head], values[i]
  35. head++
  36. i++
  37. }
  38. }
  39. values[head] = mid
  40. quickSortInt(values[:head], comparator)
  41. quickSortInt(values[head+1:], comparator)
  42. }
  43. // quickSortStr is the quick-sorting algorithm implements for string.
  44. func quickSortStr(values []string, comparator func(a, b string) int) {
  45. if len(values) <= 1 {
  46. return
  47. }
  48. mid, i := values[0], 1
  49. head, tail := 0, len(values)-1
  50. for head < tail {
  51. if comparator(values[i], mid) > 0 {
  52. values[i], values[tail] = values[tail], values[i]
  53. tail--
  54. } else {
  55. values[i], values[head] = values[head], values[i]
  56. head++
  57. i++
  58. }
  59. }
  60. values[head] = mid
  61. quickSortStr(values[:head], comparator)
  62. quickSortStr(values[head+1:], comparator)
  63. }