广告
返回顶部
首页 > 资讯 > 后端开发 > GO >golang编程开发使用sort排序示例详解
  • 892
分享到

golang编程开发使用sort排序示例详解

2024-04-02 19:04:59 892人浏览 独家记忆
摘要

golang sort package: https://studyGolang.com/articles/3360 sort 操作的对象通常是一个 slice,需要满足三个基本的接

golang sort package: https://studyGolang.com/articles/3360

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) 
}

以上就是go语言编程使用sort来排序示例详解的详细内容,更多关于go语言sort排序的资料请关注编程网其它相关文章!

您可能感兴趣的文档:

--结束END--

本文标题: golang编程开发使用sort排序示例详解

本文链接: https://www.lsjlt.com/news/157388.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作