go sort排序使用

go语言中提供了sort包执行排序的相关操作,但并不像Python那样可以直接用“.”符号调用sort()函数。

1、直接调用。go中提供了三种类型数据的排序int64 float64 string

x := []int{4, 2, 7, 4, 12, 4, 2}
fmt.Println(x)
fmt.Println(sort.IntsAreSorted(x))

sort.Ints(x)//默认升序
fmt.Println(sort.IntsAreSorted(x))
fmt.Println(x)

sort.Sort(sort.Reverse(sort.IntSlice(x)))//降序
fmt.Println(x)

运行结果:

其他两个方法调用类似 sort.Float64s();sort.Strings()

2、针对sort包中未提供的类型,如int32,float32等,需实现接口Len()、Swap()、Less()

type Int32List []int32
func (s Int32List) Len() int{return len(s)}
func (s Int32List) Swap(i,j int)  {s[i],s[j]=s[j],s[i]}
func (s Int32List) Less(i,j int) bool {return s[i]<s[j]}

完整代码如下:

package main

import "fmt"
import (
   "sort"
)
type Int32List []int32
func (s Int32List) Len() int{return len(s)}
func (s Int32List) Swap(i,j int)  {s[i],s[j]=s[j],s[i]}
func (s Int32List) Less(i,j int) bool {return s[i]<s[j]}

func main()  {
   k := []int32{3, 2, 6, 7, 9, 3, 2, 1}
   sort.Sort(Int32List(k))
   fmt.Println(k)//升序
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dailingGuo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值