Message Boards Message Boards

4 Replies
0 Total Likes
View groups...
Share this post:

Why is my sort not working?

Posted 9 years ago

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

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


Thank you for the answers. I wasn't aware that the inequality is only for numerical comparison.

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 BY: Frank Kampas

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.


returns unevaluated.

One way to get what you want is simply to evaluate

Reverse[Sort[{{l, 3}, {q, 4}, {a, 4}}]]

again assuming that the first item in each ordered pair does not have a numerical (or other assigned) value.

POSTED BY: David Reiss
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract