/ 2019-06-19
更多内容请关注微信公众号:oldboygo
Go语言 sort包提供了排序切片和用户自定义数据集的函数。
基本类型排序
1、升序排序
对于 int 、 float64 和 string 数组或是分片的排序, go 分别提供了 sort.Ints() 、 sort.Float64s() 和 sort.Strings() 函数, 默认都是从小到大排序。
package main
import (
"fmt"
"sort"
)
func main() {
intList1 := []int{2, 0, 1, 8, 0, 9, 2, 4, 1, 2}
floatList1 := []float64{4.2, 5.9, 12.3, 10.0, 50.4, 99.9, 31.4, 27.81828, 3.14}
stringList1 := []string{"o", "l", "d", "b", "o", "y", "g", "o", "l", "a", "n", "g"}
// 方法一
sort.Ints(intList1)
sort.Float64s(floatList1)
sort.Strings(stringList1)
fmt.Printf("方法一:\n%v\n%v\n%v\n", intList1, floatList1, stringList1)
// 方法二
intList2 := []int{2, 0, 1, 8, 0, 9, 2, 4, 1, 2}
floatList2 := []float64{4.2, 5.9, 12.3, 10.0, 50.4, 99.9, 31.4, 27.81828, 3.14}
stringList2 := []string{"o", "l", "d", "b", "o", "y", "g", "o", "l", "a", "n", "g"}
sort.Sort(sort.IntSlice(intList2))
sort.Sort(sort.Float64Slice(floatList2))
sort.Sort(sort.StringSlice(stringList2))
fmt.Printf("方法二:\n%v\n%v\n%v\n", intList2, floatList2, stringList2)
// 方法三
intList3 := []int{2, 0, 1, 8, 0, 9, 2, 4, 1, 2}
floatList3 := []float64{4.2, 5.9, 12.3, 10.0, 50.4, 99.9, 31.4, 27.81828, 3.14}
stringList3 := []string{"o", "l", "d", "b", "o", "y", "g", "o", "l", "a", "n", "g"}
(sort.IntSlice(intList3)).Sort()
(sort.Float64Slice(floatList3)).Sort()
(sort.StringSlice(stringList3)).Sort()
fmt.Printf("方法二:\n%v\n%v\n%v\n", intList3, floatList3, stringList3)
}
2、降序排序
sort 包下的三个类型 IntSlice 、 Float64Slice 、 StringSlice 分别实现了这三个方法, 对应排序的是 [] int 、 [] float64 和 [] string 。如果期望逆序排序, 只需要将对应的 Less 函数简单修改一下即可。
go 的 sort 包可以使用 sort.Reverse(slice) 来调换 slice.Interface.Less ,也就是比较函数,所以, int 、 float64 和 string 的逆序排序函数可以这么写:
package main
import (
"fmt"
"sort"
)
func main() {
intList := []int{2, 0, 1, 8, 0, 9, 2, 4, 1, 2}
floatList := []float64{4.2, 5.9, 12.3, 10.0, 50.4, 99.9, 31.4, 27.81828, 3.14}
stringList := []string{"o", "l", "d", "b", "o", "y", "g", "o", "l", "a", "n", "g"}
sort.Sort(sort.Reverse(sort.IntSlice(intList)))
sort.Sort(sort.Reverse(sort.Float64Slice(floatList)))
sort.Sort(sort.Reverse(sort.StringSlice(stringList)))
fmt.Printf("%v\n%v\n%v\n", intList, floatList, stringList)
}
(0)