关于go:go源码阅读sort包3种类型排序

4次阅读

共计 616 个字符,预计需要花费 2 分钟才能阅读完成。

一、介绍

go doc sort.sort 包,查看包次要性能函数
输入:

type Interface interface {Len() int
    Less(i, j int) bool
    Swap(i, j int)
}
func Sort(data Interface)

只有一个 Sort 函数,参数为实现了 len(),less(),swap(),三个办法的 Interface 接口。

二、排序整数、浮点数和字符串切片

对于 []int, []float, []string 这种元素类型是根底类型的切片应用 sort 包提供的上面几个函数进行排序。

sort.Ints
sort.Float64s
sort.Strings

应用示例如下:

func TestSort(t *testing.T) {//sort.Ints 对 []int 类型进行排序
    i := []int{4, 2, 3, 1}
    sort.Ints(i)
    fmt.Println(i) // [1 2 3 4]

    //sort.Float64s 对 []float64 类型进行排序
    f := []float64{4.2, 2.3, 3.1, 1.2}
    sort.Float64s(f)
    fmt.Println(f) // [1.2 2.3 3.1 4.2]

    //sort.Strings 对 []string 类型进行排序
    s := []string{"b", "d", "c", "a"}
    sort.Strings(s)
    fmt.Println(s) //[a b c d]
}

二、对于构造体,slice 的排序
能够参考 sort.slice

正文完
 0