1

I have a hash %d,i want the top five valued keys.I did the following wich worked but is there anything more effecient? @p=(reverse sort{$d{$a}<=>$d{$b}} keys%d)[0..4];

Votes + Comments
Good question. I think the answer is 'no' but I can't prove it.
3
Contributors
4
Replies
5
Views
5 Years
Discussion Span
Last Post by ssdeep
1

We can take the greatest five from a hash without sorting. I don't know if that makes it more efficient. For example, the following prints the five colors having the longest wavelengths.

#!/usr/bin/perl
use strict;
use warnings;

my %d = (violet => 400,
         red    => 650,
         indigo => 445,
         orange => 590,
         blue   => 475,
         yellow => 570,
         green  => 510);

my @p;

foreach my $r (0 .. 4){
    foreach my $k (keys %d){
        if (!defined$p[$r]
            or $d{$k} > $d{$p[$r]}){
            $p[$r] = $k;
        }
    }
    delete $d{$p[$r]};#After saving one of top 5, delete it from hash
}

print join "\n", @p;
0

Thanks for the tip,haven't thought of that.Is there more effecient performance wise?

1
use Sort::Key::Top qw(rnkeytop);
my @top = rnkeytop { $d{$_} } 5 => keys %d;

See also Selection algorithm

Edited by sfandino: Add pointer to selection algorithm on the Wikipedia

0

sfandino thanks but i think d5e5's suggestion is more effecient.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.