Go具有Sort包,可用于對(duì)內(nèi)置以及用戶定義的數(shù)據(jù)類型進(jìn)行排序。
sort包具有不同的方法來對(duì)不同的數(shù)據(jù)類型進(jìn)行排序,例如Ints(),F(xiàn)loat64s(),Strings()等。
我們可以使用AreSorted()方法(例如Float64sAreSorted(),IntsAreSorted()等)來檢查值是否排序。
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: ", s輸出:
Ints: [5 8 10 20] floatValue: [5.5 8.5 10.5 20.5] Strings: [Mohan Raj Roy] Sorted: true
假設(shè)我們想根據(jù)字符串的長(zhǎng)度對(duì)字符串?dāng)?shù)組進(jìn)行排序,我們還可以實(shí)現(xiàn)自己的排序模式。為此,我們必須實(shí)現(xiàn)在排序接口中定義的自己的Less,Len和Swap方法。
然后,我們必須將數(shù)組轉(zhuǎn)換為實(shí)現(xiàn)的類型。
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]