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.

I'm sure I'll be embarrassed by the answer, but I don't understand why I get the following result:

list = {{9, "b"}, {4, "a"}, {7, "k4"}, {6, "k3"}, {5, "w"}}  

This works:

Sort[list]  
(* {{4, "a"}, {5, "w"}, {6, "k3"}, {7, "k4"}, {9, "b"}}*)

This works:

Sort[list, #1[[1]] > #2[[1]] &]   
(*{{9, "b"}, {7, "k4"}, {6, "k3"}, {5, "w"}, {4, "a"}}  *)

But this fails:

Sort[list, #1[[2]] < #2[[2]] &]   
(*{{9, "b"}, {4, "a"}, {7, "k4"}, {6, "k3"}, {5, "w"}}*)

Question:

Why would it work using SortBy[] and not Sort[]?

share|improve this question
    
SortBy[list, #[[2]] &]? –  Öskå Jul 25 '13 at 14:36
    
@Öskå SortBy[] does work, but I think Sort[] should work too. –  George Wolfe Jul 25 '13 at 14:41
8  
The Less operator (<) remains unevaluated on strings, thus your last result. –  Leonid Shifrin Jul 25 '13 at 14:42
    
@LeonidShifrin I saw that the problem occurs only with strings, but I didn't know why. Is SortBy[] the only approach, or is there another that allows Sort[] to work (or is this issue unimportant)? –  George Wolfe Jul 25 '13 at 14:47
2  
No, it is not a flaw in Sort. You have to use a correct comparison function, which you did not, for strings. –  Leonid Shifrin Jul 25 '13 at 14:51
show 2 more comments

2 Answers

up vote 9 down vote accepted

Leonid Shifrin has pointed out why the 3rd sample fails: Less doesn't "compare" strings.

Still, it's possible to use Sort, with the addition of OrderedQ:

Sort[list, OrderedQ[{#1[[2]], #2[[2]]}] &]

{{4, "a"}, {9, "b"}, {6, "k3"}, {7, "k4"}, {5, "w"}}

share|improve this answer
    
Thanks, everyone. –  George Wolfe Jul 25 '13 at 14:54
add comment

Another sort of short Sort is

#/@Sort[#/@list]&@Reverse

(* ==> {{4, "a"}, {9, "b"}, {6, "k3"}, {7, "k4"}, {5, "w"}} *)

This puts the strings in first position before sorting, and then puts the strings back in second place afterwards.

share|improve this answer
2  
This sort of short sort seems surprisingly simple –  George Wolfe Jul 25 '13 at 18:03
1  
+1. Another obscure way to do this, avoiding Map: Composition[#, Sort, #] &[Reverse[#, {2}] &][list] –  Leonid Shifrin Jul 25 '13 at 18:11
2  
@LeonidShifrin Ah, a last-resort re-sort. I think you can just use Reverse[#, 2] for this list. –  Jens Jul 25 '13 at 18:21
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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