# How to sort first two numbers in sublists

Given

t7 = t8 = {{3, 5, 1}, {19, 2, 9}, {4, 3, 1}, {19, 0, 8}};


I want to Sort the first two numbers in each sublist and keep the third number in its position. I can do it by

t7[[All, {1, 2}]] = Sort /@ t7[[All, {1, 2}]]
t7


or

 t8[[All, {1, 2}]] = # & /@ #[[Ordering[#]]] & /@ t8[[All, 1 ;; 2]]
t8


to get

{{3, 5, 1}, {2, 19, 9}, {3, 4, 1}, {0, 19, 8}}


But there must be more elegant ways to do it. Any idea?

You can use SubsetMap for this:

SubsetMap[Sort,{1,2}] /@ {{3,5,1}, {19,2,9}, {4,3,1}, {19,0,8}}


{{3, 5, 1}, {2, 19, 9}, {3, 4, 1}, {0, 19, 8}}

• Thank you! Good function! Didn't know it. Aug 28, 2021 at 3:39
Append[Sort@Most@#, Last@#]& /@ t7


Or with Through:

Flatten@Through[{Sort@*Most, Last}@#] & /@ t7


Let sf2 stand for sortfirst2,

sf2 = # /. {a_, b_, c___} /; a > b -> {b, a, c} &

t7 = {{3, 5, 1}, {19, 2, 9}, {4, 3, 1}, {19, 0, 8}};

sf2 /@ t7

{{3, 5, 1}, {2, 19, 9}, {3, 4, 1}, {0, 19, 8}}

• Or Replace[t7, {a_, b_, c___} /; a > b -> {b, a, c}, 1] (to act only at level 1) or t7 /. {a_, b_, c___} /; a > b -> {b, a, c} (because the condition makes it so that the entire expression doesn't change and it goes to subexpressions). Aug 27, 2021 at 20:47
list = {{3, 5, 1}, {19, 2, 9}, {4, 3, 1}, {19, 0, 8}};


Using Comap (new in 14.0) and Splice (new in 13.1)

Comap[{Splice @* Sort @* Most, Last}] /@ list


{{3, 5, 1}, {2, 19, 9}, {3, 4, 1}, {0, 19, 8}}

Using Query

Query[All, {Splice @* Sort @* Most, Last}] @ list


{{3, 5, 1}, {2, 19, 9}, {3, 4, 1}, {0, 19, 8}}

list = {{3, 5, 1}, {19, 2, 9}, {4, 3, 1}, {19, 0, 8}};


Using ReplaceList:

ReplaceList[list, {___, s : {__}, ___} :> {Splice@Sort@Most@s, Last@s}]

(*{{3, 5, 1}, {2, 19, 9}, {3, 4, 1}, {0, 19, 8}}*)