... wastefully filtering the sorted results through reverse ...
Somewhere/when, I remember seeing a note to the effect that the Perl compiler optimizes the instruction sequence reverse sort so that a "native" reversed or descending sort occurs; i.e., there is no difference in time/space complexity between reversed and non-reversed sort. Looking through the docs just now does not turn up anything about this for me. However, experimentation (with Perl version 5.14 only) shows it is true, at least in the default sort (i.e., no comparison block) case:
c:\@Work\Perl>perl -wMstrict -le
"use List::Util qw(shuffle);
;;
print 'shuffling...';
my @rra = shuffle 1 .. 10_000_000;
;;
print 'sorting...';
my (@sorted, $start, $dur_asc, $dur_des);
;;
$start = time;
@sorted = sort @rra;
$dur_asc = time - $start;
;;
@sorted = ();
;;
$start = time;
@sorted = reverse sort @rra;
$dur_des = time - $start;
;;
print 'ascending (default sort): ', $dur_asc;
print 'descending (reverse sort): ', $dur_des;
;;
sub pra { print qq{@{ $_[0] }[ 0 .. 9 ] @{ $_[0] }[ -10 .. -1 ]}; }
"
shuffling...
sorting...
ascending (default sort): 57
descending (reverse sort): 53
Calls to pra() at various points against the @rra and @sorted arrays show expected results: at least the first and last few elements of these arrays are always as expected.
One oddity: The second sort performed is always just a few seconds faster than the first. This is true regardless of whether the reversed sort is performed first or second. I attribute this small but consistent speed difference to the Perl interpreter having already allocated an internal, intermediate array for the first sort that still exists at the time of the second sort and so does not need re-allocation, thus saving a bit of time. However, I can't see how to prove this speculation. Any thoughts?
Update: Limited experimentation with version 5.8.9 shows essentially the same behavior.
Give a man a fish: <%-(-(-(-<
|