douzhi1924 2013-08-20 19:12
浏览 508
已采纳

如何对整数Go的切片进行反向排序?

I am trying to reverse-sort a slice of integers in Go.

  example := []int{1,25,3,5,4}
  sort.Ints(example) // this will give me a slice sorted from 1 to the highest number

How do I sort it so that it goes from highest to lowest? so [25 5 4 3 1]

I have tried this

sort.Sort(sort.Reverse(sort.Ints(keys)))

Source: http://golang.org/pkg/sort/#Reverse

However, I am getting the error below

# command-line-arguments
./Roman_Numerals.go:31: sort.Ints(keys) used as value
  • 写回答

2条回答 默认 最新

  • duanliao6789 2013-08-20 19:19
    关注

    sort.Ints is a convenient function to sort a couple of ints. Generally you need to implement the sort.Interface interface if you want to sort something and sort.Reverse just returns a different implementation of that interface that redefines the Less method.

    Luckily the sort package contains a predefined type called IntSlice that implements sort.Interface:

    keys := []int{3, 2, 8, 1}
    sort.Sort(sort.Reverse(sort.IntSlice(keys)))
    fmt.Println(keys)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?