Go具有排序包,可用于对内置以及用户定义的数据类型进行排序。
sort包具有不同的方法来对不同的数据类型进行排序,例如Ints(),Float64s(),Strings()等。
我们可以使用AreSorted()方法(例如Float64sAreSorted(),IntsAreSorted()等)来检查值是否已排序。
链接:https://www.learnfk.comhttps://www.learnfk.com/go/go-sorting.html
来源:LearnFk无涯教程网
package main import ( "sort" "fmt" ) func main() { intValue := []int{10, 20, 5, 8} sort.Ints(intValue) fmt.Println("Ints: ", intValue) floatValue := []float64{10.5, 20.5, 5.5, 8.5} sort.Float64s(floatValue) fmt.Println("floatValue: ", floatValue) stringValue := []string{"Raj", "Mohan", "Roy"} sort.Strings(stringValue) fmt.Println("Strings:", stringValue) str := sort.Float64sAreSorted(floatValue) fmt.Println("Sorted: ", str) }
输出:
Ints: [5 8 10 20] floatValue: [5.5 8.5 10.5 20.5] Strings: [Mohan Raj Roy] Sorted: true
我们还可以实现自己的排序模式,假设我们想根据字符串的长度对字符串数组进行排序。为此,我们必须实现在排序接口中定义的自己的Less,Len和Swap方法。
然后,我们必须将数组转换为实现的类型。
package main import "sort" import "fmt" type OrderByLengthDesc []string func (s OrderByLengthDesc) Len() int { return len(s) } func (str OrderByLengthDesc) Swap(i, j int) { str[i], str[j] = str[j], str[i] } func (s OrderByLengthDesc) Less(i, j int) bool { return len(s[i]) > len(s[j]) } func main() { city := []string{"New York", "London","Washington","Delhi"} sort.Sort(OrderByLengthDesc(city)) fmt.Println(city) }
输出:
[Washington New York London Delhi]
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)