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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |