Go Sorting
Go Sorting
Go 有 sort 包,可用于对内置和用户定义的数据类型进行排序。
sort 包有对不同数据类型进行排序的不同方法,例如 Ints()、Float64s()、Strings() 等。
我们可以使用 AreSorted() 方法(例如 Float64sAreSorted())检查值是否已排序, IntsAreSorted() 等
Go Sort Example
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
我们也可以实现我们自己的排序模式,假设我们想根据长度对字符串数组进行排序。为了做到这一点,我们必须实现自己在 sort 接口中定义的 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]