# Understanding reverse sorting

There is probably something really simple I’m missing here but I can’t get my head around how reverse sorting works.

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

To sort a slice, I do:

``````sort.Sort(myslice)
``````

But to sort in reverse I have to do:

``````sort.Sort(sort.Reverse(myslice))
``````

From the docs, “Reverse returns the reverse order for data.” so shouldn’t `sort.Reverse` sort in reverse order and then `sort.Sort` put the slice back into normal order again? Instead if I just do `sort.Reverse` nothing appears to happen.

You are cheating

The documentation says sort.Sort gets a sort.Interface, not a slice!

The interface implements three methods, Len, Swap and Less. Less, given two elements of the slice, returns true if the first is element is to be put before the second element.

sort.Reverse takes the sort.Interface and just negates Less, inverting its meaning.

Makes sense?

I did notice the interface mention rather than a slice but didn’t really take it in. That description is a good one and makes sense, I’ll build a couple of examples up so I can see it in action. Thanks.

I’ve had a play and it all seems to make sense, how does this look for sorting
a key/value struct by either keys or values and being able to reverse the sort?

Instead of p.reverse (and associated code), you can indeed use sort.Reverse.

Also, I would make two different sorting interface implementations for the “sortByKey” boolean. Basically, just make two types:

``````type pairSortValue []Pair
type pairSortKey []Pair
``````

… and implement Len(), Swap() and Less() for both.

When you want to sort:

``````sort.Sort(pairSortValue(ps))
sort.Sort(sort.Reverse(pairSortKey(ps))
``````

(where ps is a slide of Pair.)

OK, that makes sense. Twists my mind a bit but I get it.

Thanks.

1 Like

I’ve rewritten it, it looks much better now.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.