3、深入理解排序
sort 包中有一个 sort.Interface 接口,该接口有三个方法 Len() 、 Less(i,j) 和 Swap(i,j) 。 通用排序函数 sort.Sort 可以排序任何实现了 sort.Inferface 接口的对象(变量)。对于 [] int 、[] float64 和 [] string 除了使用特殊指定的函数外,还可以使用改装过的类型 IntSclice 、 Float64Slice 和 StringSlice , 然后直接调用它们对应的 Sort() 方法;因为这三种类型也实现了 sort.Interface 接口, 所以可以通过 sort.Reverse 来转换这三种类型的 Interface.Less 方法来实现逆向排序, 这就是前面最后一个排序的使用。
下面使用了一个自定义(用户定义)的 Reverse 结构体, 而不是 sort.Reverse 函数, 来实现逆向排序。
package main
import (
"fmt"
"sort"
)
// 自定义的 Reverse 类型
type Reverse struct {
sort.Interface // 这样,Reverse可以接纳任何实现了sort.Interface的对象
}
// Reverse 只是将其中的 Inferface.Less 的顺序对调了一下
func (r Reverse) Less(i, j int) bool {
return r.Interface.Less(j, i)
}
func main() {
ints := []int{5, 2, 6, 3, 1, 4}
sort.Ints(ints) // 特殊排序函数,升序
fmt.Println("after sort by Ints:t", ints)
doubles := []float64{2.3, 3.2, 6.7, 10.9, 5.4, 1.8}
sort.Float64s(doubles)
fmt.Println("after sort by Float64s:t", doubles) // [1.8 2.3 3.2 5.4 6.7 10.9]
strings := []string{"hello", "good", "students", "morning", "people", "world"}
sort.Strings(strings)
fmt.Println("after sort by Strings:t", strings) // [good hello mornig people students world]
ipos := sort.SearchInts(ints, -1) // int 搜索
fmt.Printf("pos of 5 is %d thn", ipos)
dpos := sort.SearchFloat64s(doubles, 20.1) // float64 搜索
fmt.Printf("pos of 5.0 is %d thn", dpos)
fmt.Printf("doubles is asc ? %vn", sort.Float64sAreSorted(doubles))
doubles = []float64{3.5, 4.2, 8.9, 100.98, 20.14, 79.32}
// sort.Sort(sort.Float64Slice(doubles)) // float64 排序方法 2
// fmt.Println("after sort by Sort:t", doubles) // [3.5 4.2 8.9 20.14 79.32 100.98]
(sort.Float64Slice(doubles)).Sort() // float64 排序方法 3
fmt.Println("after sort by Sort:t", doubles) // [3.5 4.2 8.9 20.14 79.32 100.98]
sort.Sort(Reverse{sort.Float64Slice(doubles)}) // float64 逆序排序
fmt.Println("after sort by Reversed Sort:t", doubles) // [100.98 79.32 20.14 8.9 4.2 3.5]
}
sort.Ints / sort.Float64s / sort.Strings 分别来对整型/浮点型/字符串型slice进行排序。然后是有个测试是否有序的函数。还有分别对应的 search 函数,不过,发现搜索函数只能定位到如果存在的话的位置,不存在的话,位置是不对的。
关于一般的数组排序,程序中显示了,有 3 种方法!目前提供的三种类型 int,float64 和 string 呈现对称的,也就是你有的,对应的我也有。关于翻转排序或是逆向排序,就是用个翻转结构体,重写










