Maybe a hash is not the best data structure to solve your problem.

I would use a binary tree or a B-tree, on the grounds that inserting is relatively cheap, and the inserted items are already sorted. Finding the first N items in sorted order would just be a simple matter of walking down the tree while keeping a count. When the count is over, you stop listing.

Now, what tool provides such mechanism? A DBMS for sure. You insert your values in a table with an index on the columns you need to keep in order, and you get your list faster than you could possibly do with some hard coded algorithms in your script.

Using a database, your sorted list would be just a combination of ORDER BY and LIMIT (choose a DBMS that supports such feature).

You would pay with slower insertion (inserting records into a table is slower than using a hash, but you would minimize the retrieval time, since sorting (by index) is already done.)

BTW, if merlyn were here, he would say that he has a column on this subject (or maybe two).


In reply to Re: *Fastest* way to print a hash sorted by value by cchampion
in thread *Fastest* way to print a hash sorted by value by smellysocks

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.