# Why does Sort fail in this simple example?

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[]?

-
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
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
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

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"}}

-
Thanks, everyone. – George Wolfe Jul 25 '13 at 14:54

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.

-
This sort of short sort seems surprisingly simple – George Wolfe Jul 25 '13 at 18:03
+1. Another obscure way to do this, avoiding Map: Composition[#, Sort, #] &[Reverse[#, {2}] &][list] – Leonid Shifrin Jul 25 '13 at 18:11
@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