How do I reverse sort a slice of integer Go?

Go

Go Problem Overview


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

Go Solutions


Solution 1 - Go

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)

Solution 2 - Go

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]

Solution 3 - Go

Instead of using two function calls and a cast, you can do it with just 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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsamolView Question on Stackoverflow
Solution 1 - Gotux21bView Answer on Stackoverflow
Solution 2 - GozzzzView Answer on Stackoverflow
Solution 3 - GoZomboView Answer on Stackoverflow