I don't see a really perlish way to do this, so my approach would be to repeatedly sort the data using heaps, first taking the bottom n elements, then the next n elements. This can be done relatively efficiently using heaps, except that you have to sort the data keys %hash / n times. I think you can optimize the second passes onwards by caching the offset items at positions n, 2*n and so on, so you get to discard items that are "too high" earlier on. I'm not sure whether not inserting items that will get discarded anyway will save you much time.

Alternatively, you could look at whether your external sort program can handle the data size, then I'd write out the keys using each and read them back in using while (<$fh>) {.

Which tradeoff is faster will really depend, because with the first approach, you're basically sorting your data multiple times, while with the second approach, your external sort program needs a strategy to sort the data.


In reply to Re: In-place sort with order assignment by Corion
in thread In-place sort with order assignment by BrowserUk

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.