# select the smallest $M elements; while ($new_element = $dbh->fetchrow) { if ($heap->size < $M) { # build a heap of size M $heap->insert($new_element); } elsif ($element < $heap->largest) { # maintain a heap containing # the smallest M elements # seen so far $heap->remove_largest; $heap->insert($element); } }