Search code examples
wolfram-mathematicalist-manipulation

sorting with changes to the other part in mathematica


I am just wondering:

given a list {{{3,1,2},{4,2,5}},{{7,1},{2,4}}}, I want to sort the first component, then have the second component change as the first one does. The desired result is {{{1,2,3},{2,5,4}},{{1,7},{4,2}}}.

How can I do this? Many thanks for your help.


Solution

  • I suggest:

    #[[ All, Ordering@#[[1]] ]] & /@ list
    

    This is shorter than Michael's, and nearly twice as efficient.

    micSort = {#[[Ordering[#]]], #2[[Ordering[#]]]} & @@@ # &;
    
    wizSort = #[[All, Ordering@#[[1]]]] & /@ # &;
    
    a = RandomInteger[100, {2400, 2, 15}];
    
    micSort@a === wizSort@a
    First@Timing@Do[#@a, {25}] & /@ {micSort, wizSort}
    
    Out[1]= True
    
    Out[2]= {0.453, 0.282}