# how to sort the expression not based on the Heads in Times?

Is there any way i can sort the following expression ?

a[k, l] b[i, j]


so that i would have:

b[i, j] a[k,l]


Mathematica does the ordering based on the heads. is there anyway to change it ?

• To be clear: you are seeking a way to sort the elements of that expression based on the lexicographical ordering of the arguments to those elements ? – High Performance Mark Feb 7 at 15:33
• @High Performance Mark i want to order the expression based on their arguments rather than the heads. so if i have a[m,n] b[i,j] c[k,l] i want it to be like b[i,j] c[k,l] a[m,n] – user49047 Feb 7 at 16:15
• The expression you show here has head Times: spaces are interpreted as multiplication (use FullForm to check if you're unsure). Times is a symbol with the attribute Orderless, meaning that it will always sort its arguments in canonical order. The only way to have something close to what you want is Inactivate[b[i, j] a[k, l], Times] – Sjoerd Smit Feb 7 at 16:15
• Inactive[Times] @@ SortBy[List @@ expr, First] – Bob Hanlon Feb 7 at 16:29

with the help of Bob Hanlon:

axx = HoldForm[
NonCommutativeMultiply @@
SortBy[List @@ (a[k, l] b[i, j]), First]] // ReleaseHold

axx //. NonCommutativeMultiply[a_, Y___] :> HoldForm[Times[a, Y]]

SortBy[Inactivate[a[m, n] b[i, j] c[k, l], Times], Function[x, #[[x]]]/@ Range[Length@#]&] /.
Inactive[Times] -> HoldForm@*Times


b[i,j] c[k,l] a[m,n]