文章目录
- 1. Slice() 不稳定排序 2. SliceStable() 稳定排序 3. SliceIsSorted() 判断是否已排序 结构体定义如下,我们完全可以定义更复杂的结构体: // 结构体定义 type test struct { value int str string }
- package main import ( “fmt” “sort” ) // 结构体定义 type test struct { value int str string } func main() { s := make([]test, 5) s[0] = test{value: 2, str: “test2”} s[1] = test{value: 4, str: “test4”} s[2] = test{value: 1, str: “test1”} s[3] = test{value: 5, str: “test5”} s[4] = test{value: 3, str: “test3”} fmt.Println(“初始化结果:”) fmt.Println(s) // 从小到大排序(不稳定排序) sort.Slice(s, func(i, j int) bool { if s[i].value < s[j].value { return true } return false }) fmt.Println(“n从小到大排序结果:”) fmt.Println(s) // 从小到大排序(稳定排序) sort.SliceStable(s, func(i, j int) bool { if s[i].value < s[j].value { return true } return false }) // 是否从小到大排序 bLess := sort.SliceIsSorted(s, func(i, j int) bool { if s[i].value < s[j].value { return true } return false }) fmt.Printf(“数组s是否从小到大排序,bLess:%vn”, bLess) // 从大到小排序(不稳定排序) sort.Slice(s, func(i, j int) bool { if s[i].value > s[j].value { return true } return false }) fmt.Println(“n从大到小排序结果:”) fmt.Println(s) // 是否从大到小排序 bMore := sort.SliceIsSorted(s, func(i, j int) bool { if s[i].value > s[j].value { return true } return false }) fmt.Printf(“数组s是否从大到小排序,bMore:%vn”, bMore) }
目录
- golang结构体slice排序
- 排序函数
- 结果
- 完整代码
- 总结
go语言的slice()不仅仅可以对int类型的数组进行排序,还可以对struct类型的数组进行排序
- 1. Slice() 不稳定排序
- 2. SliceStable() 稳定排序
- 3. SliceIsSorted() 判断是否已排序
结构体定义如下,我们完全可以定义更复杂的结构体:
// 结构体定义
type test struct {
value int
str string
}

package main
import (
"fmt"
"sort"
)
// 结构体定义
type test struct {
value int
str string
}
func main() {
s := make([]test, 5)
s[0] = test{value: 2, str: "test2"}
s[1] = test{value: 4, str: "test4"}
s[2] = test{value: 1, str: "test1"}
s[3] = test{value: 5, str: "test5"}
s[4] = test{value: 3, str: "test3"}
fmt.Println("初始化结果:")
fmt.Println(s)
// 从小到大排序(不稳定排序)
sort.Slice(s, func(i, j int) bool {
if s[i].value < s[j].value {
return true
}
return false
})
fmt.Println("n从小到大排序结果:")
fmt.Println(s)
// 从小到大排序(稳定排序)
sort.SliceStable(s, func(i, j int) bool {
if s[i].value < s[j].value {
return true
}
return false
})
// 是否从小到大排序
bLess := sort.SliceIsSorted(s, func(i, j int) bool {
if s[i].value < s[j].value {
return true
}
return false
})
fmt.Printf("数组s是否从小到大排序,bLess:%vn", bLess)
// 从大到小排序(不稳定排序)
sort.Slice(s, func(i, j int) bool {
if s[i].value > s[j].value {
return true
}
return false
})
fmt.Println("n从大到小排序结果:")
fmt.Println(s)
// 是否从大到小排序
bMore := sort.SliceIsSorted(s, func(i, j int) bool {
if s[i].value > s[j].value {
return true
}
return false
})
fmt.Printf("数组s是否从大到小排序,bMore:%vn", bMore)
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持风君子博客。
您可能感兴趣的文章:
- Golang将接口文档字段转结构体的实践指南
- Golang实现结构体和Json格式数据之间的互相转换
- Golang中的结构体和反射示例详解
- 一文详解下划线字段在golang结构体中的应用
- golang结构体指针的实现
- Golang实现根据某个特定字段对结构体的顺序进行排序