The problem I have with your solution isn't so much the "cleanness", as well its inefficiency. You will be checking for direction for every comparison made by the sort - instead of checking it once.

In either case, you still have an O(n log n) sort. If you are really concerned about the difference in efficiency here, you might be better off programming in C or assembly. With perl, it's not even so easy to determine the efficiency with that level of granularity. For instance, how does your reverse() compare to the additional branches in the OP's code?

It seemed the OP was hoping to make his code cleaner and therefore easier to read and maintain. In terms of efficiency, he could be saving minutes to hours of programmer time over the lifetime of this program compared to the mere seconds of machine time your optimization may save. And when you compare costs, the difference is likely to be even more significant because developer time generally costs a lot more than machine time.

None of this is to say the solution you suggested is a bad one. It isn't. Regardless of efficiency questions, it is clearer. If he's going to use this same sort more often than once, though, sticking it in a sub might be a good idea (in which case, of course, it should be given a better name than the OP's original mysort().) Two separate subs for ascending and descending might be a good idea in that case too.

-sauoq
"My two cents aren't worth a dime.";

In reply to Re^2: sort direction by sauoq
in thread sort direction by rsiedl

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.