Golang 基础教程

Golang 控制语句

Golang 函数 & 方法

Golang 结构体

Golang 切片 & 数组

Golang 字符串(String)

Golang 指针

Golang 接口

Golang 并发

Golang 异常(Error)

Golang 其他杂项

Go 语言排序(Sort)

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: ", s

输出:

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]