Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I have a problem regarding list sorting. Let's say I have a list of lists obtained using Subsets[], of the form

{
{2, 3, 4}, {2, 3, 5}, {2, 3, 6}, {2, 4, 5}, {2, 4, 6},
{2, 5, 6}, {3, 4, 5}, {3, 4, 6}, {3, 5, 6}, {4, 5, 6}
}

I would like to sort it element by element from the end, in descending order - so that all lists with 6 as the last element are first, sorted again in the same way by their second element, and sorted again by their first one, like so:

{
{4, 5, 6}, {3, 5, 6}, {2, 5, 6}, {3, 4, 6}, {2, 4, 6}, 
{2, 3, 6}, {3, 4, 5}, {2, 4, 5}, {2, 3, 5}, {2, 3, 4}
}

I am interested in a general solution as I need to apply this to lists of n-element permutations, not just triples like here.

I can easily sort them by a single element using SortBy, but I cannot grasp my head around a way to sort them recursively, step by step, n times. I would appreciate any help.

share|improve this question
    
This should work but I don't know much about sorting so don't ask :) Composition[ Reverse, Reverse /@ # &, Sort, Reverse /@ # & ][list] –  Kuba Jan 26 at 19:07
    
@Kuba Perfect. Thank you. –  sps Jan 26 at 19:14
add comment

marked as duplicate by Mr.Wizard Jan 26 at 22:12

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2 Answers

up vote 5 down vote accepted

I would use this:

Reverse @ SortBy[list, Reverse]
share|improve this answer
    
Embarrassingly I didn't use this method my answer to the question I marked as a duplicate. I'm going to incorporate it into my answer there, with credit to you. +1 –  Mr.Wizard Jan 26 at 22:01
1  
The performance of this code could be improved in the case of ties by using the stable sort syntax: SortBy[list, {Reverse}] –  Mr.Wizard Jan 26 at 22:37
    
@Mr.Wizard, thanks for the reminder. For some reason the stable sort syntax just won't stick in my brain. –  Simon Woods Jan 27 at 10:25
add comment

I can't beat Simon's answer in simplicity, but an equivalent version, similar to Kuba's is:

With[{reverse = Reverse[#, 2] &}, Composition[Reverse, reverse, Sort, reverse]]@list

or even:

Composition[Reverse[#, {1, 2}] &, Sort, Reverse[#, 2] &]@list
share|improve this answer
add comment

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