Go - 排序

Go - 排序 首页 / Golang入门教程 / Go - 排序

Go具有排序包,可用于对内置以及用户定义的数据类型进行排序。

sort包具有不同的方法来对不同的数据类型进行排序,例如Ints(),Float64s(),Strings()等。

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

链接:https://www.learnfk.comhttps://www.learnfk.com/go/go-sorting.html

来源:LearnFk无涯教程网

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

我们还可以实现自己的排序模式,假设我们想根据字符串的长度对字符串数组进行排序。为此,我们必须实现在排序接口中定义的自己的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]

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

深入剖析Kubernetes -〔张磊〕

MySQL实战45讲 -〔林晓斌〕

Python核心技术与实战 -〔景霄〕

TypeScript开发实战 -〔梁宵〕

MongoDB高手课 -〔唐建法(TJ)〕

说透敏捷 -〔宋宁〕

检索技术核心20讲 -〔陈东〕

分布式系统案例课 -〔杨波〕

A/B测试从0到1 -〔张博伟〕

好记忆不如烂笔头。留下您的足迹吧 :)