Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Re: Re: Heap sorting in perl

by blakem (Monsignor)
on Apr 05, 2003 at 19:58 UTC ( #248332=note: print w/replies, xml ) Need Help??

in reply to Re: Heap sorting in perl
in thread Heap sorting in perl

A heap is a specialized datastructure that can be thought of as an "automatically sorted array" given a somewhat scaled down definition of "sorted". Sorted in this case means that the largest element is always easy to find and remove, and inserting new elements is also easy.

Given that, our steps to find the smallest M elements would be:

  1. Build a heap from our first M items
  2. Compare next item to largest element in heap
  3. Replace largest with new if new < largest
  4. Repeat steps 2 and 3 for all remaining items

As you can see, this is very similar to the strategy you proposed. In fact, you could view heaps as a datastructure designed specifically to implement this algorithm efficiently.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://248332]
[1nickt]: Corion I feel that way a lot when I look at the news...
[1nickt]: Brethren, I just noticed in the CPAN ticker Retry, which led me to Attempt, by Mark Fowler. Does anyone have experience with either of these utilities?
[Corion]: No. Back when I toyed with the idea, I found that writing the loop explicitly was usually less code than passing the configuration+ callback to the retrier...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (7)
As of 2017-05-24 12:28 GMT
Find Nodes?
    Voting Booth?