golang struct数组排序_golang 结构体 slice 排序-Go语言中文社区

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)

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值