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

2022-07-20,,,,

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排序的资料请关注其它相关文章!

《golang编程开发使用sort排序示例详解.doc》

下载本文的Word格式文档,以方便收藏与打印。