RE: Sort
- To: mathgroup at smc.vnet.net
- Subject: [mg19179] RE: [mg19152] Sort
- From: "Ersek, Ted R" <ErsekTR at navair.navy.mil>
- Date: Tue, 10 Aug 1999 02:52:42 -0400
- Sender: owner-wri-mathgroup at wolfram.com
Hermann Meier wrote:
------------------------
Sort is not reliable. Try the following (Mathematica Version 4):
In[1]:=
Sort[{0, -Sqrt[2], 5}]
Out[1]=
{0, 5, -Sqrt[2]}
-----------------------------
The code below should improve Sort and I know of
no cases where this modified version would mess up.
You could put this in your (init.m).
If anyone wants to know how it works let me know.
In[1]:=
HiddenSymbols`ModifySort=True;
Unprotect[Sort];
Sort[expr_]:=
Block[{HiddenSymbols`ModifySort},
Sort[expr,
If[NumericQ[#1]&&NumericQ[#2],
Re[#1]<Re[#2]||
(Re[#1]==Re[#2]&&Im[#1]>Im[#2]),
OrderedQ[{#1,#2}]
]&
]
];
Protect[Sort];
In[5]:=
Sort[{0,x,5,t,-Sqrt[2]}]
Out[5]=
{-Sqrt[2], 0, 5, t, x}
--------------------------
Notice the patch above isn't used when you provide a sorting function.
In[6]:=
Sort[{0,5,-Sqrt[2]}, (#1>#2)&]
Out[6]=
{5, 0, -Sqrt[2]}
---------------------
Regards,
Ted Ersek