What I think you should do is collect is larger number of "top" items, and once you get over a threshold, say, if @top contains 100 entries where you need only 20, you can sort and only keep the top 20, and drop the 80 items below it. That should divide your count of sorts by 80, as it would only sort again once you added 80 more items; or (possibly a lot) more, if you only keep the items that are not above the score of the current item #20. Still, a factor 80 is already significant, even though the sort itself will be slower. (Sorting 100 items should take, ooh, 6 or 7 times longer than sorting 20 items, I guess.)
Here's a proof of concept implementation (untested) for both ideas:
and with threshold:my $N = 20; my $collect = 5 * $N; while (<>) { my ($id, $score) = split ' '; push @top, [$id, $score]; if(@top > $collect) { @top = sort { $b->[1] <=> $a->[1] } @top; splice @top, $N; } } if(@top > $N) { @top = sort { $b->[1] <=> $a->[1] } @top; splice @top, $N; }
my $N = 20; my $collect = 5 * $N; my $threshold; while (<>) { my ($id, $score) = split ' '; push @top, [$id, $score] if !defined $threshold or $score >= $thre +shold; if(@top > $collect) { @top = sort { $b->[1] <=> $a->[1] } @top; splice @top, $N; $threshold = $top[-1][1]; } } if(@top > $N) { @top = sort { $b->[1] <=> $a->[1] } @top; splice @top, $N; }
In reply to Re^2: Dealing with Hash Table
by bart
in thread Dealing with Hash Table
by ŞuRvīvőr
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |