Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang sort slice ascending or descending

Tags:

sorting

go

I need to sort a slice of a type that is coming from a 3rdparty package. Based on some condition the order must be ascending or descending.

The solution I come up with is:

type fooAscending []foo  func (v fooAscending) Len() int           { return len(v) } func (v fooAscending) Swap(i, j int)      { v[i], v[j] = v[j], v[i] } func (v fooAscending) Less(i, j int) bool { return v[i].Amount < v[j].Amount }  type fooDescending []foo  func (v fooDescending) Len() int           { return len(v) } func (v fooDescending) Swap(i, j int)      { v[i], v[j] = v[j], v[i] } func (v fooDescending) Less(i, j int) bool { return v[i].Amount > v[j].Amount }  if someCondition {     sort.Sort(fooAscending(array)) } else {     sort.Sort(fooDescending(array)) } 

Is there a better way to do this. 13 lines of code for this task and most of it is duplicated, seems a bit too much.

like image 755
gsf Avatar asked Jun 08 '16 06:06

gsf


People also ask

How do you sort a slice in go?

As of Go 1.8, there is an easier way to sort a slice that does not require you to define new types. 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.

How does sort slice work in Golang?

In Go language, you can sort a slice with the help of Slice() function. This function sorts the specified slice given the provided less function. The result of this function is not stable. So for stable sort, you can use SliceStable.

How do you sort a string of slices?

To sort a slice of strings in Go programming, use sort package. sort package offers sorting for builtin datatypes and user defined datatypes, through which we can sort a slice of strings. The sorting or strings happen lexicographically. Meaning a is less than b , b is less than c , and so on.


2 Answers

As of Go 1.8, there is an easier way to sort a slice that does not require you to define new types. You simply pass an anonymous function to the sort.Slice function.

a := []int{5, 3, 4, 7, 8, 9} sort.Slice(a, func(i, j int) bool {     return a[i] < a[j] }) for _, v := range a {     fmt.Println(v) } 

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

like image 109
Franck Jeannin Avatar answered Sep 24 '22 12:09

Franck Jeannin


You're looking for sort.Reverse. That will let you say:

sort.Sort(sort.Reverse(fooAscending(s))) 
like image 37
cnicutar Avatar answered Sep 22 '22 12:09

cnicutar