排序是我们业务中最常用的功能之一,我们要学会如何通过go语言来实现排序,下面我们来看实例。
float64的类型数据的排序例子
代码语言:javascript复制package main
import (
"sort"
"fmt"
)
func main() {
//float64进行排序,从小到大
a1 := []float64{1.1, 2.2, 5.6, 8.2, 0.3, 0.8}
sort.Float64s(a1)
fmt.Println(a1)
//这个是判断a1 是否按照从小到大排序了
if sort.Float64sAreSorted(a1) {
fmt.Println("a1 sort ok")
}
}
返回结果
代码语言:javascript复制[0.3 0.8 1.1 2.2 5.6 8.2]
a1 sort ok
下面我们看int类型的数据排序例子
代码语言:javascript复制package main
import (
"sort"
"fmt"
)
func main() {
a2 := []int{1, 2, 4, 3, 67, 9, 3, 0}
sort.Ints(a2)
fmt.Println(a2)
//这个是判断a2 是否按照从小到大排序了
if sort.IntsAreSorted(a2) {
fmt.Println("a2 sort ok")
}
}
返回结果如下
代码语言:javascript复制[0 1 2 3 3 4 9 67]
a2 sort ok
下面我们看一下string类型的排序使用
代码语言:javascript复制package main
import (
"sort"
"fmt"
)
func main() {
//按照字母顺序排序
a3 := []string{"a", "b", "cc", "d", "er", "ll", "aa", "dd"}
sort.Strings(a3)
fmt.Println(a3)
if sort.StringsAreSorted(a3) {
fmt.Println("a3 sort ok")
}
}
返回结果
代码语言:javascript复制[a aa b cc d dd er ll]
a3 sort ok
最后我们来看一下自定义排序的使用,我这里介绍三种方式,我们直接来看代码
代码语言:javascript复制package main
import (
"sort"
"fmt"
)
type Person struct {
Name string
Percent int
}
type Person2 struct {
Name string
Percent int
}
type Persons []Person2
func (this Persons) Len() int {
return len(this)
}
func (this Persons) Less(i, j int) bool {
return this[i].Percent > this[j].Percent
}
func (this Persons) Swap(i, j int) {
this[i], this[j] = this[j], this[i]
}
func (this Persons) Sort() {
sort.Sort(this)
}
type Person3 struct {
Name string
Percent int
}
type PersonSlice []Person3
func (s PersonSlice) Len() int { return len(s) }
func (s PersonSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s PersonSlice) Less(i, j int) bool { return s[i].Percent > s[j].Percent }
func main() {
//自定义数据类型排序1
p1 := make([]Person, 4)
p1[0] = Person{Name: "aa", Percent: 99}
p1[1] = Person{Name: "bb", Percent: 22}
p1[2] = Person{Name: "cc", Percent: 55}
p1[3] = Person{Name: "ee", Percent: 100}
fmt.Println("原始:", p1)
sort.SliceStable(p1, func(i, j int) bool {
return p1[i].Percent > p1[j].Percent
})
fmt.Println("排序后", p1)
//自定义排序2
p2 := make([]Person2, 4)
p2[0] = Person2{Name: "aa", Percent: 44}
p2[1] = Person2{Name: "bb", Percent: 33}
p2[2] = Person2{Name: "cc", Percent: 22}
p2[3] = Person2{Name: "ee", Percent: 100}
fmt.Println("原始:", p2)
p3 := Persons(p2)
p3.Sort()
fmt.Println("排序后", p3)
//自定义排序2
a := PersonSlice{
{
Name: "AAA",
Percent: 55,
},
{
Name: "BBB",
Percent: 22,
},
{
Name: "CCC",
Percent: 0,
},
{
Name: "DDD",
Percent: 22,
},
{
Name: "EEE",
Percent: 11,
},
}
fmt.Println("原始:", a)
sort.Stable(a)
fmt.Println("排序后", a)
}
下面我们看一下结果
代码语言:javascript复制原始:[{aa 99} {bb 22} {cc 55} {ee 100}]
排序后 [{ee 100} {aa 99} {cc 55} {bb 22}]
原始:[{aa 44} {bb 33} {cc 22} {ee 100}]
排序后 [{ee 100} {aa 44} {bb 33} {cc 22}]
原始:[{AAA 55} {BBB 22} {CCC 0} {DDD 22} {EEE 11}]
排序后 [{AAA 55} {BBB 22} {DDD 22} {EEE 11} {CCC 0}]
好了,排序的例子差不多了,有什么问题欢迎交流。