Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reverse sort a slice of integer Go?

Tags:

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 
like image 373
samol Avatar asked Aug 20 '13 19:08

samol


People also ask

How do you reverse a sort order?

sort() method. This method requires two parameters i.e. the list to be sorted and the Collections. reverseOrder() that reverses the order of an element collection using a Comparator. The ClassCastException is thrown by the Collections.

How do you sort slices?

Use the function sort. Slice . It sorts a slice using a provided function less(i, j int) bool . To sort the slice while keeping the original order of equal elements, use sort.

How do you sort an array in ascending order in Golang?

You simply pass an anonymous function to the sort. Slice function. This will sort in ascending order, if you want the opposite, simply write a[i] > a[j] in the anonymous function.


2 Answers

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) 
like image 118
tux21b Avatar answered Sep 23 '22 01:09

tux21b


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] 
like image 40
zzzz Avatar answered Sep 26 '22 01:09

zzzz