# Why is my sort not working?

Posted 8 years ago
3555 Views
|
4 Replies
|
0 Total Likes
|
 I am new to Mathematica so perhaps there is something silly I am doing. This simple test does not do what I expect. Sort[{{l, 3}, {q, 4}, {a, 4}}, #1[[1]] > #2[[1]] &] The output is {{a, 4}, {q, 4}, {l, 3}}. I was expecting it to be ordered as {{q, 4}, {l, 3}, {a, 4}}. Changing the test to use the numeric part works as expected.What am I doing wrong?
4 Replies
Sort By:
Posted 8 years ago
 A general solution may be to define a specific comparison function that works on the structure you want. myOrder[a_, b_] := OrderedQ[{b[[1, 2]], a[[1, 2]]}] Sort[{{{1, l, 1}, 3}, {{3, q, 2}, 4}, {{2, a, 3}, 5}}, myOrder[#1, #2] &] works as expected {{{3, q, 2}, 4}, {{1, l, 1}, 3}, {{2, a, 3}, 5}} Thanks
Posted 8 years ago
 Thank you for the answers. I wasn't aware that the inequality is only for numerical comparison.
Posted 8 years ago
 In[7]:= Sort[{{l, 3}, {q, 4}, {a, 4}}, ToCharacterCode[ToString[#1[[1]]]][[1]] > ToCharacterCode[ToString[#2[[1]]]][[1]] &] Out[7]= {{q, 4}, {l, 3}, {a, 4}} 
Posted 8 years ago
 The "greater than" sign is for numerical comparison. It does not order symbols so your expression does nothing to the sorting. For example (assuming that a, q and l have no numerical values associated with them--i.e., they are pure symbols. `a