8
$\begingroup$

I am looking at the two functions SortBy and ReverseSort.

SortBy[{{1, 2, 3}, {2, 3, 1}, {3, 1, 2}, {2, 2}}, Last]

{{2, 3, 1}, {2, 2}, {3, 1, 2}, {1, 2, 3}}

How do I sort this by the last element, but in the reverse order? I want to get this:

{{1, 2, 3}, {3, 1, 2}, {2, 2}, {2, 3, 1}}

$\endgroup$
1
  • 3
    $\begingroup$ may be I am missing your question. Is this what you want? Reverse@SortBy[{{1,2,3},{2,3,1},{3,1,2},{2,2}},Last] which gives {{1,2,3},{3,1,2},{2,2},{2,3,1}} $\endgroup$
    – Nasser
    Nov 5, 2017 at 18:21

2 Answers 2

9
$\begingroup$

If you don't care about the ordering of {3, 1, 2} and {2, 2}, do this:

SortBy[{{1, 2, 3}, {2, 3, 1}, {3, 1, 2}, {2, 2}}, Minus @* Last]
   {{1, 2, 3}, {2, 2}, {3, 1, 2}, {2, 3, 1}}

Otherwise, add a second sorting criterion; e.g.

SortBy[{{1, 2, 3}, {2, 3, 1}, {3, 1, 2}, {2, 2}}, {Minus @* Last, Minus @* Length}]
   {{1, 2, 3}, {3, 1, 2}, {2, 2}, {2, 3, 1}}

or just wrap the sorting criterion in a list (per Alan):

SortBy[{{1, 2, 3}, {2, 3, 1}, {3, 1, 2}, {2, 2}}, {Minus @* Last}]
   {{1, 2, 3}, {3, 1, 2}, {2, 2}, {2, 3, 1}}
$\endgroup$
2
  • $\begingroup$ I think SortBy[{{1, 2, 3}, {2, 3, 1}, {3, 1, 2}, {2, 2}}, {Minus@*Last}] will ensure a stable sort. $\endgroup$
    – Alan
    Nov 5, 2017 at 21:08
  • $\begingroup$ Ah, right. Let me add that note. $\endgroup$ Nov 5, 2017 at 21:10
7
$\begingroup$

Using:

l = {{2, 3, 1}, {2, 2}, {3, 1, 2}, {1, 2, 3}};

One option, just using Sort:

Sort[l, Last[#2] < Last[#1] &]

Another option, using SortBy and Reverse:

Reverse@SortBy[l, Last]

I'm not completely sure about ReverseSort (my version of Mathematica does not have it), but I imagine something like this would be at least a start (not too sure about "tie" cases, or how concerned you are with them):

ReverseSort[l, Last[#1] < Last[#2] &]

Not an expert on this, so anyone should feel free to correct me if I'm wrong.

$\endgroup$
1
  • 2
    $\begingroup$ I'd expect SortBy to be considerably faster than Sort with a custom comparison function (because each custom comparison requires a Mathematica evaluation) $\endgroup$
    – Szabolcs
    Nov 5, 2017 at 21:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.