If your data set isn't too large, just sort. If it is large, do a partial sort. Here's an example of each method:
use strict; use warnings; my @x = qw( c d e f k l m n ); my @y = qw( 4 6 5 2 9 7 8 3 ); # Full sort method: -------------------------------------------------- +- my @sorted_idx = sort { $y[$a] <=> $y[$b] } 0 .. $#y; print "The five highest valued names:\n"; print_range( reverse @sorted_idx [ $#sorted_idx-4 .. $#sorted_idx ] ); print "The five lowest valued names:\n"; print_range( @sorted_idx[ 0 .. 4 ] ); # Partial sort method: ----------------------------------------------- +-- use Sort::Key::Top qw( keytopsort ); print "The five highest valued names:\n"; print_range( reverse keytopsort { $y[$_] } -5 => 0 .. $#y ); print "The five lowest valued named:\n"; print_range( keytopsort { $y[$_] } 5 => 0 .. $#y ); # Helper sub: -------------------------------------------------------- +-- sub print_range { my @indices = @_; print "\t$x[$_] => $y[$_] at position $_\n" for @indices; }
It's my understanding that the partial sort method (Sort::Key::Top) implements the "Linear General Selection Algorithm" (Wikipedia article), which provides a very efficient solution.
Another option (that is also supported by CPAN) is to build two heaps; one for mins, and one for max's, and then pop the first five elements off of each.
Either of the two solutions I provided will produce the following output:
The five highest valued names: k => 9 at position 4 m => 8 at position 6 l => 7 at position 5 d => 6 at position 1 e => 5 at position 2 The five lowest valued names: f => 2 at position 3 n => 3 at position 7 c => 4 at position 0 e => 5 at position 2 d => 6 at position 1
Dave
In reply to Re: How can one find five max values and five min values with positions in descending and ascending order from arrays?
by davido
in thread How can one find five max values and five min values with positions in descending and ascending order from arrays?
by supriyoch_2008
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |