golang中的排序

x33g5p2x  于2021-11-12 转载在 Go  
字(1.2k)|赞(0)|评价(0)|浏览(544)

golang中排序的底层逻辑

golang中排序最底层的逻辑是是这段代码sort.Sort

  1. // Sort sorts data.
  2. // It makes one call to data.Len to determine n and O(n*log(n)) calls to
  3. // data.Less and data.Swap. The sort is not guaranteed to be stable.
  4. func Sort(data Interface) {
  5. n := data.Len()
  6. quickSort(data, 0, n, maxDepth(n))
  7. }

而它的参数是一个接口类型sort.Interface,下面是它的定义

  1. type Interface interface {
  2. Len() int
  3. Less(i, j int) bool
  4. Swap(i, j int)
  5. }

也就意味着,所有想要使用快速排序算法来排序的类型,只要实现了sort.Interface接口,就可以使用sort.Sort方法来排序。

内建的排序方法

在定制排序规则之前,我们先来看下golang的官方包中包含的基本排序方法

  1. strArr := []string{"hello", "5", "world", "0", "golang", "123"}
  2. sort.Strings(strArr)
  3. fmt.Println(strArr) // 输出 [0 123 5 golang hello world]

官方包中提供了sort.Strings()来给字符串slice排序,sort.Ints()给整型slice排序,等等。

自定义排序规则

假设我想实现的逻辑是在已有的字符串排序规则之上,让数字出现在最后,我就可以通过定义一个类并实现sort.Interface来实现

  1. type NumberLastStringSlice []string
  2. func (x NumberLastStringSlice) Len() int { return len(x) }
  3. func (x NumberLastStringSlice) Less(i, j int) bool {
  4. xIsDigit := unicode.IsDigit([]rune(x[i])[0])
  5. jIsDigit := unicode.IsDigit([]rune(x[j])[0])
  6. if (xIsDigit && jIsDigit) || (!xIsDigit && !jIsDigit) {
  7. return x[i] < x[j]
  8. }
  9. return !xIsDigit
  10. }
  11. func (x NumberLastStringSlice) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
  1. sort.Sort(NumberLastStringSlice(strArr))
  2. fmt.Println(strArr) // 输出 [golang hello world 0 123 5]

相关文章

最新文章

更多