Hello all,

I'm trying to wrap my head around how the sort function does it's deed.There are several examples as to different uses for sort, but I would like to know how the operation takes place.

@numbers = (7, 12, 49, 44); @sorted = sort { $a <=> $b } @numbers;

I understand the return codes of 1, 0, and -1 but what happens after the first comparison? I'm assuming element 0 is the first instance of $a and element 1 is $b. Those two are compared. The return value would be -1 since 7 is less than 12. So now what happens? We have established that element 0 is less than element 1. Is element 0 now compared to the rest of the elements with each subsequent element taking over the value of $b for comparison? If something is smaller than element 0, is that value now used for $a until all elements to compare have been exhausted? Once the first compare has been exhausted to find the smallest number that value is now assigned to the new array as element zero, sort of like a king of the hill for the smallest number?

Sorry for the odd post but I've seen several examples of what happens in the end but not what is happening along the way for the sort command.

Mike W

In reply to how sort works by Complex13

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.