cmp compairs strings. Consider for a moment a comparison of the string 'b' with 'ac'. Which string comes first in ascending order? That's easy; 'ac' comes first because 'a' is less than 'b'.

Now look at '4' and '13' as strings. The string on the left contains a single character; '4'. The string on the right contains two characters, '1' and '3'. The leftmost character (1) is compared to the only character in the other string (4), and since 1 is less than 4, the string with the digits '1' and '3' (13) is positioned closer to the start of an ascending order list than the string with only a '4' in it. When doing a string comparison, you're not comparing the number 13 with the number 4. You're comparing the string containing a 1 and a 3 with the string containing only a 4.

This behavior is sometimes casually referred to as "ASCIIbetical sorting", because it's not strictly alphabetical, and not exactly the way a dictionary works, but does make sense in the context of a given character set. One big difference between asciibetical sorting and alphabetical sorting is that with true alphabetical sorting 'A' and 'a' would be right next to each other in priority instead of being separated by B-Z and a few other symbols.


Dave


In reply to Re: Sorting sorts 13 as less than 2 by davido
in thread Sorting sorts 13 as less than 2 by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.