Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
Dear Monks,
I need to sort an array which is having positive & negative numbers.it should take these into account & give max number & min number.
for example ,if my array has
@array = (99, 67, 0, -100, -38, 98)
then it should sort and give me -100 is min value & 99 is max value.
currently i am using "sort" which is not working on the negative numbers.Please help!
Thanks in advance.
Re: sort an array with +ve & -ve numbers in it
by ikegami (Patriarch) on Apr 03, 2009 at 09:10 UTC
|
The default sort criteria sorts lexically (alphabetically). You need to specify your own sort criteria.
my @sorted = sort { $a <=> $b } @numbers;
my $min = $sorted[0];
my $max = $sorted[-1];
| [reply] [d/l] |
|
| [reply] [d/l] [select] |
Re: sort an array with +ve & -ve numbers in it
by jwkrahn (Abbot) on Apr 03, 2009 at 10:51 UTC
|
You don't need to sort the array to get the minimum and maximum values, a simple loop will do:
$ perl -le'
my @array = ( 99, 67, 0, -100, -38, 98 );
my ( $min, $max ) = @array;
for my $element ( @array ) {
$min = $element if $min > $element;
$max = $element if $max < $element;
}
print "Min = $min and Max = $max";
'
Min = -100 and Max = 99
| [reply] [d/l] |
|
my @array = ( 99, 67, 0, -100, -38, 98);
my ($min, $max) = (sort @array)[0,-1];
| [reply] [d/l] |
|
Easier and simpler, but less efficient (O n log n, perhaps) than jwkrahn's approach (O n). Of course this won't matter for small data sets.
| [reply] |
|
|
As already stated by ikegami, you really need to use the numerical sort: sort {$a <=> $b} @array
Try changing your data set to my @array = ( -10, 99, 67, 0, -100, -38, 98) and using that sort routine. This is probably the problem the OP is having. You're going to get -10 as the minimum.
| [reply] [d/l] [select] |
|
|
Re: sort an array with +ve & -ve numbers in it
by nagalenoj (Friar) on Apr 03, 2009 at 09:20 UTC
|
Hope, this will help you to know how sort works. Sort | [reply] |
Re: sort an array with +ve & -ve numbers in it
by vinoth.ree (Monsignor) on Apr 03, 2009 at 10:01 UTC
|
You can also get the minimum value by using the $#sortedThis will hold the last element's index in the array
| [reply] [d/l] |
Re: sort an array with +ve & -ve numbers in it
by JavaFan (Canon) on Apr 03, 2009 at 09:24 UTC
|
i am using "sort" which is not working on the negative numbers.
Well, I'm a bit baffled by this. I guess what you are doing wrong - you're probably sorting alphabetically. But that doesn't work with positive numbers either.
| [reply] |
|
|