robiticus has the right idea, in my eye: you don't have to sort on every iteration. However his code looks complex to me and at first sight I still get the impression he still sorts for every entry.

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:

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; }
and with threshold:
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 &#350;uRvīv&#337;r

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.