snippetgoCritical
golang sort slice ascending or descending
Viewed 0 times
ascendingsortslicedescendinggolang
Problem
I need to sort a slice of a type that is coming from a 3rd party package. Based on some condition the order must be ascending or descending.
The solution I come up with is:
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.
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 }
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.
Solution
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
This will sort in ascending order, if you want the opposite, simply write
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.Code Snippets
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)
}Context
Stack Overflow Q#37695209, score: 218
Revisions (0)
No revisions yet.