my ($largest, $smallest) = (-9e9,9e9); # in
+itialize to the wrong extremes
...
for my $v (@array) { # [a
+nonymous monk]'s [id://1203660]: single pass through loop, without so
+rting; more efficient than brostad's single sort
$largest = $v if $v > $largest;
$smallest = $v if $v < $smallest;
}
The only quarrel I have with this implementation is that it depends on assumptions about the smallest and largest representable numbers (the wrongest extremes) in the system. Even if the assumptions are true in a given system, all bets are off if you move, e.g., to a different platform: from a 32-bit float to a 64-, 80- or who-knows-how-many-bit float. And if they're not true:
c:\@Work\Perl\monks>perl -wMstrict -le
"my @array = (-9e9-123, -9e9-234);
;;
my ($largest, $smallest) = (-9e9, 9e9);
;;
for my $elem (@array) {
$largest = $elem if $elem > $largest;
$smallest = $elem if $elem < $smallest;
}
print qq{smallest: $smallest; largest: $largest};
"
smallest: -9000000234; largest: -9000000000
Taking the initial smallest/largest value from the array itself is bulletproof: either the initializer is already the smallest/largest value, or some other value will be found in the array that is smaller/larger.
c:\@Work\Perl\monks>perl -wMstrict -le
"my @array = (-9e9-123, -9e9-234);
;;
my ($largest, $smallest) = ($array[0], $array[0]);
;;
for my $elem (@array) {
$largest = $elem if $elem > $largest;
$smallest = $elem if $elem < $smallest;
}
print qq{smallest: $smallest; largest: $largest};
"
smallest: -9000000234; largest: -9000000123
Give a man a fish: <%-{-{-{-<