本网站(662p.com)打包出售,且带程序代码数据,662p.com域名,程序内核采用TP框架开发,需要联系扣扣:2360248666 /wx:lianweikj
精品域名一口价出售:1y1m.com(350元) ,6b7b.com(400元) , 5k5j.com(380元) , yayj.com(1800元), jiongzhun.com(1000元) , niuzen.com(2800元) , zennei.com(5000元)
需要联系扣扣:2360248666 /wx:lianweikj
golang编程开发使用sort排序示例详解
iamitnan · 305浏览 · 发布于2021-11-16 +关注

这篇文章主要为大家介绍了go语言编程开发使用sort来排序示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步早日升职加薪

golang sort package: golang中sort包用法 - Go语言中文网 - Golang中文社区

sort 操作的对象通常是一个 slice,需要满足三个基本的接口,并且能够使用整数来索引

// A type, typically a collection, that satisfies sort.Interface can be
// sorted by the routines in this package. The methods require that the
// elements of the collection be enumerated by an integer index.
type Interface interface {
// Len is the number of elements in the collection.
Len() int
// Less reports whether the element with
// index i should sort before the element with index j.
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
}


ex-1 对 []int 从小到大排序  

package main
import (
"fmt"
"sort"
)
type IntSlice []int
func (s IntSlice) Len() int { return len(s) }
func (s IntSlice) Swap(i, j int){ s[i], s[j] = s[j], s[i] }
func (s IntSlice) Less(i, j int) bool { return s[i] < s[j] }
func main() {
a := []int{4,3,2,1,5,9,8,7,6}
sort.Sort(IntSlice(a))
fmt.Println("After sorted: ", a) 
}


 ex-2 使用 sort.Ints 和 sort.Strings 

golang 对常见的 []int 和 []string 分别定义了 IntSlice 和 StringSlice, 实现了各自的排序接口。而 sort.Ints 和 sort.Strings 可以直接对 []int 和 []string 进行排序, 使用起来非常方便 

package main
import (
"fmt"
"sort"
)
func main() {
a := []int{3, 5, 4, -1, 9, 11, -14}
sort.Ints(a)
fmt.Println(a)
ss := []string{"surface", "ipad", "mac pro", "mac air", "think pad", "idea pad"}
sort.Strings(ss)
fmt.Println(ss)
sort.Sort(sort.Reverse(sort.StringSlice(ss)))
fmt.Printf("After reverse: %v\n", ss)
}


ex-3 使用 sort.Reverse 进行逆序排序 

如果我们想对一个 sortable object 进行逆序排序,可以自定义一个type。但 sort.Reverse 帮你省掉了这些代码

package main
import (
"fmt"
"sort"
)
func main() {
a := []int{4,3,2,1,5,9,8,7,6}
sort.Sort(sort.Reverse(sort.IntSlice(a)))
fmt.Println("After reversed: ", a)
}


ex-4 使用 sort.Stable 进行稳定排序 

sort.Sort 并不保证排序的稳定性。如果有需要, 可以使用 sort.Stable 

package main
import (
"fmt"
"sort"
)
type person struct {
Name string
Age int
}
type personSlice []person
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].Age < s[j].Age }
func main() {
a := personSlice {
{
Name: "AAA",
Age: 55,
},
{
Name: "BBB",
Age: 22,
},
{
Name: "CCC",
Age: 0,
},
{
Name: "DDD",
Age: 22,
},
{
Name: "EEE",
Age: 11,
},
}
sort.Stable(a)
fmt.Println(a)
}


相关推荐

PHP实现部分字符隐藏

沙雕mars · 1322浏览 · 2019-04-28 09:47:56
Java中ArrayList和LinkedList区别

kenrry1992 · 906浏览 · 2019-05-08 21:14:54
Tomcat 下载及安装配置

manongba · 966浏览 · 2019-05-13 21:03:56
JAVA变量介绍

manongba · 960浏览 · 2019-05-13 21:05:52
什么是SpringBoot

iamitnan · 1084浏览 · 2019-05-14 22:20:36
加载中

0评论

评论
分类专栏
小鸟云服务器
扫码进入手机网页