We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,613 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

effecient way to sort hash by values?can we do it without sort?

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];

3
Contributors
4
Replies
1 Day
Discussion Span
1 Year Ago
Last Updated
5
Views
Question
Answered
ssdeep
Light Poster
27 posts since Oct 2009
Reputation Points: 19
Solved Threads: 0
Skill Endorsements: 0

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;
d5e5
Practically a Posting Shark
831 posts since Sep 2009
Reputation Points: 162
Solved Threads: 163
Skill Endorsements: 1

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

ssdeep
Light Poster
27 posts since Oct 2009
Reputation Points: 19
Solved Threads: 0
Skill Endorsements: 0
use Sort::Key::Top qw(rnkeytop);
my @top = rnkeytop { $d{$_} } 5 => keys %d;

See also Selection algorithm

sfandino
Newbie Poster
1 post since Dec 2011
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0

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

ssdeep
Light Poster
27 posts since Oct 2009
Reputation Points: 19
Solved Threads: 0
Skill Endorsements: 0
Question Answered as of 1 Year Ago by d5e5 and sfandino

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0669 seconds using 2.69MB