Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

This question already has an answer here:

Sort[{13, Sqrt[157], Sqrt[163]}]

(*{13, Sqrt[157], Sqrt[157]}*)

Sort[{13, Sqrt[157], Sqrt[157]}, #1 < #2 &]

(*{Sqrt[157], Sqrt[157], 13}*)

This seems totally broken to me, 13 should always be > Sqrt[163] and Sqrt[157].

And I only figured out what the problem was when I pasted this into this message - seeing the Sqrt[] funtion rather than the radical sign in the notebook.

From my (admittedly limited) understanding of Mathematica, I can sort see how the Sqrt[] would get in the way, but it seems quite painful to have to run output from functions such as Minimize through N before being able to use Sort or SortBy.

So, I guess my question is, is this expected behaviour that I just have to learn to live with, or a bug?

share|improve this question

marked as duplicate by Mr.Wizard Dec 21 '13 at 15:58

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3  
This behavior is fully documented on the help page of Sort. You can change it using Sort's optional second argument (also documented on the same page). –  Sjoerd C. de Vries Dec 21 '13 at 14:30
    
Possible duplicate of mathematica.stackexchange.com/q/2729/131 ? –  Yves Klett Dec 21 '13 at 15:29
    
@Yves Yup. Closing again. –  Mr.Wizard Dec 21 '13 at 15:57
    
I have closed this a second time. If anyone has something nontrivial to add that doesn't apply to the marked duplicate please get my attention and I shall reopen it. –  Mr.Wizard Dec 21 '13 at 16:00
add comment

1 Answer 1

up vote 3 down vote accepted

I briefly closed this question, then realized I had more to say than easily fits into the comments.

This is documented behavior so in a way you have to learn to live with it, but the work-around is very simple: use SortBy

SortBy[{13, Sqrt[157], Sqrt[163]}, N]
{Sqrt[157], Sqrt[163], 13}

This is far superior to using Sort with a second argument as it preserves the lower algorithmic complexity of the default sort rather than the pairwise comparison that is used with custom ordering functions.

You can improve performance somewhat further if you are interested in only numeric order, or more specifically the default ordering of expressions as converted by N. This is done by using {N} as the second argument of SortBy which results in a stable sort. When using N (bare, without {}) ties will be broken using the default ordering function on the original expression.

share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.