# Basic question Sort criteria

Can you explain the following codes? (output of codes)

I know that

there is the default ordering for any expression in Mathematica

and Sort uses the default ordering, if no sorting criteria is specified.

Sort[{1 + a[3], 2 - a[2], a[2] - 2 a[3], 4 - a[2]}]
{2 - a[2], 4 - a[2], a[2] - 2 a[3], 1 + a[3]}

Sort[ToString /@ {1 + a[3], 2 - a[2], a[2] - 2 a[3], 4 - a[2]}]
{"1 + a[3]", "2 - a[2]", "4 - a[2]", "a[2] - 2 a[3]"}

Sort[{1 + a[3], 2 - a[2], a[2] - 2 a[3], 4 - a[2]}, ToString[#1] < ToString[#2] &]
{1 + a[3], 2 - a[2], a[2] - 2 a[3], 4 - a[2]}


The leftmost part of the 1st output {2 - a[2], 4 - a[2], a[2] - 2 a[3], 1 + a[3]} is

2, 4, a, 1

No matter how we sort 2, 4, a, 1, I don't think 2, 4, a, 1 is a possible order.

The 2nd output {"1 + a[3]", "2 - a[2]", "4 - a[2]", "a[2] - 2 a[3]"} is agreeable. The leftmost character is

1, 2, 4, a

And it is in the normal dictionary order.

I think the 3rd output {1 + a[3], 2 - a[2], a[2] - 2 a[3], 4 - a[2]} should be consistent with 2nd output. But

1, 2, a, 4

is not consistent with 2nd output.

• For the first example it's treating the expressions like polynomials in a where the indexed value is equivalent to the power of the term in the polynomial. i.e. replace a[n] with a^n. It looks like they're being sorted by the order of the polynomial first, then by the coefficients of the highest order term. For the third example the problem is just that < doesn't work on strings so you're getting your list back in the order you put it in. Try "a"<"b" - it doesn't evaluate to a boolean. Feb 20, 2023 at 16:54

The leftmost part of the 1st output ... I don't think 2, 4, a, 1 is a possible order

This is kind of a moot point. These are expressions, and Mathematica has a canonical order for expressions. Not only is this a "possible order", it is manifestly "the order". Mathematica presumably "knows why it wants" that order, and it's sort of pointless to try to fight against that or even spend much time thinking about it.

I think the 3rd output ... should be consistent with 2nd output.

This is just a mistake in understanding. If you read the documentation for Less (aka <), it has caveats about inputs that are not real numbers.

The function that you're looking for here is Order:

testExpressions = {1 + a[3], 2 - a[2], a[2] - 2 a[3], 4 - a[2]};
Sort[testExpressions, Order[ToString[#1], ToString[#2]] &]


But since Order is the default anyway, a simpler way to sort these according to a dictionary sort would be to use SortBy:

SortBy[testExpressions, ToString]

• Thank you! especially the explanation of Less. My workaround was L[[Ordering[ToString /@ L]]]. I believe it is equal to Sort[L, Order[ToString[#1], ToString[#2]] &]. Feb 20, 2023 at 23:11