Code to find nth largest number in an array

Posted by user136104 on Stack Overflow See other posts from Stack Overflow or by user136104
Published on 2010-03-25T08:37:10Z Indexed on 2010/03/25 8:53 UTC
Read the original article Hit count: 260

Filed under:

I have written following code in perl

#!/usr/bin/perl

@array = (3,6,8,1,2);

my $second_largest = 0;
my $largest = 0;

for (@array)
{
   if($_ > $largest)
   {
       $second_largest = $largest;
       $largest = $_;
   }
   if($_ > $second_largest && $_ < $largest)
   {
        $second_largest = $_;
   }
}
print "Second largest::".$second_largest;
print "largest::".$largest;

But I need a general code to find out "Nth" largest and smallest number of an array

Please help me

© Stack Overflow or respective owner

Related posts about perl