Go排序

Go语言有一个sort包,可以用于对内置和用户定义的数据类型进行排序。

sort包提供了不同的方法来对不同的数据类型进行排序,比如Ints()、Float64s()、Strings()等。

我们可以使用AreSorted()方法(如Float64sAreSorted()、IntsAreSorted()等)来检查值是否已经排序。

Go排序示例

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.Interface中定义的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]

标签: Golang, Golang下载, Golang教程, Golang技术, Golang学习, Golang学习教程, Golang语言, Golang开发, Golang入门教程, Golang进阶教程, Golang高级教程, Golang面试题, Golang笔试题, Golang编程思想