How do I reverse sort a slice of integer Go?

huangapple go评论67阅读模式
英文:

How do I reverse sort a slice of integer Go?

问题

你可以使用sort.Sort函数和sort.Reverse类型来实现将切片中的整数按照从高到低的顺序进行排序。以下是你可以尝试的代码:

package main

import (
	"fmt"
	"sort"
)

func main() {
	example := []int{1, 25, 3, 5, 4}
	sort.Sort(sort.Reverse(sort.IntSlice(example)))
	fmt.Println(example)
}

这将输出 [25 5 4 3 1],即按照从高到低的顺序对切片进行了排序。

英文:

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

答案1

得分: 96

sort.Ints 是一个方便的函数,用于对一组整数进行排序。通常,如果你想要对某些东西进行排序,你需要实现 sort.Interface 接口,而 sort.Reverse 则返回一个重新定义了 Less 方法的该接口的不同实现。

幸运的是,sort 包中包含一个预定义类型叫做 IntSlice,它实现了 sort.Interface 接口:

keys := []int{3, 2, 8, 1}
sort.Sort(sort.Reverse(sort.IntSlice(keys)))
fmt.Println(keys)
英文:

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)

答案2

得分: 8

package main

import (
	"fmt"
	"sort"
)

func main() {
	example := []int{1, 25, 3, 5, 4}
	sort.Sort(sort.Reverse(sort.IntSlice(example)))
	fmt.Println(example)
}

Playground


输出:

[25 5 4 3 1]
英文:
package main

import (
        "fmt"
        "sort"
)

func main() {
        example := []int{1, 25, 3, 5, 4}
        sort.Sort(sort.Reverse(sort.IntSlice(example)))
        fmt.Println(example)
}

Playground


Output:

[25 5 4 3 1]

答案3

得分: 7

使用sort.Slice而不是使用两个函数调用和一个类型转换,可以简化代码:

package main

import (
   "fmt"
   "sort"
)

func main() {
   example := []int{1,25,3,5,4}
   sort.Slice(example, func(a, b int) bool {
      return example[b] < example[a]
   })
   fmt.Println(example)
}

更多信息请参考:https://golang.org/pkg/sort#Slice

英文:

Instead of using two function calls and a cast, you can do it with just sort.Slice:

package main

import (
   &quot;fmt&quot;
   &quot;sort&quot;
)

func main() {
   example := []int{1,25,3,5,4}
   sort.Slice(example, func(a, b int) bool {
      return example[b] &lt; example[a]
   })
   fmt.Println(example)
}

https://golang.org/pkg/sort#Slice

huangapple
  • 本文由 发表于 2013年8月21日 03:12:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/18343208.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定