# Sort with assumptions

I have a list which looks like this

list = {0, Subscript[x,7], -Subscript[x,3]-Subscript[x,9], -Subscript[x,9]};

and all the $$x_i$$'s are positive semidefinite (i.e. nonnegative) real numbers. I would like to be able to sort this into

sortedlist = {-Subscript[x,3]-Subscript[x,9], -Subscript[x,9], 0, Subscript[x,7]}

How do I achieve this? I tried

Assuming[Subscript[x,3] > 0 && Subscript[x,7] > 0 && Subscript[x,9] > 0, Sort[list]]

But this obviously does not work. In general, I'd like to be able to impose more constraints on the $$x_i's$$ when they're being sorted.

• An interesting idea, but a symbolic list where you have an ordering for all the elements is rare – mikado Mar 19 at 21:31

Here is a possibility:

sortWithAssumptions[list_, assum_] := Module[{order},
order[a_, b_] := Simplify[a < b, assum];
Sort[list, order]
]


sortWithAssumptions[
{0,Subscript[x,7],-Subscript[x,3]-Subscript[x,9],-Subscript[x,9]},
Subscript[x,3]>0&&Subscript[x,7]>0&&Subscript[x,9]>0
] //TeXForm


$$\left\{-x_3-x_9,-x_9,0,x_7\right\}$$

Another example:

sortWithAssumptions[
{0,Subscript[x,7],-Subscript[x,3]-Subscript[x,9],-Subscript[x,9], Subscript[x,9]},
Subscript[x,3]>0&&Subscript[x,7]>0&&Subscript[x,9]>0&&Subscript[x,7]<Subscript[x,9]
] //TeXForm


$$\left\{-x_3-x_9,-x_9,0,x_7,x_9\right\}$$

• Thank you, Carl! – leastaction Mar 19 at 21:38

list[[Ordering[list /. _Subscript -> 1]]]


{-Subscript[x, 3] - Subscript[x, 9], -Subscript[x, 9], 0, Subscript[x, 7]}

So basically we sort it the way it would be sorted with all subscripts == 1.

• Thanks! Seems to work like a charm, but can you shed some light on why? – leastaction Mar 19 at 21:31
• @leastaction just take a look at list /. _Subscript -> 1 and at Ordering[list /. _Subscript -> 1]. – Kuba Mar 19 at 21:32
• I see, so you basically assigned the value $x_i = 1$ to each $x_i$. It works in this case, but generically, $x_i$'s may be different. – leastaction Mar 19 at 21:36
• @leastaction sure, which means there isn't only one correct answer and every valid within constraints is correct. – Kuba Mar 19 at 21:38
Sort[list, TrueQ@Simplify[#1 < #2, _Subscript > 0] &]

(* Out: {-Subscript[x, 3] - Subscript[x, 9], -Subscript[x, 9], 0, Subscript[x, 7]} *)


In this case, we can use RankedMin and FullSimplify to get the answer you seek

Assuming[
Subscript[x, 3] > 0 && Subscript[x, 7] > 0 && Subscript[x, 9] > 0,
FullSimplify[Table[RankedMin[list, i], {i, 1, Length[list]}]]]
(* {-Subscript[x, 3] - Subscript[x, 9], -Subscript[x, 9], 0, Subscript[x, 7]} *)


This has the advantage of not returning a (potentially) wrong answer if the sort order is uncertain.