this is a small sub that can be used in situations where you have a large array to be sorted, but you really need only the first N elements of the sorted array.
you can think of it as something like the SQL SELECT * FROM foo ORDER BY bar LIMIT 10 (MySQL, Postgres) or SELECT TOP 10 * FROM foo ORDER BY bar (MSSQL).
of course, this has been thought of as an optimization, but to deserve the name of optimization it should really be implemented in C (XS/Inline/whatever you want). it could still perform quickier than a full sort, I suspect, particularly if your comparison function is very expensive.
SYNOPSIS
my @topten = sort_top(10, sub { $a <=> $b }, @huge_array);
sub sort_top {
my($top, $func, @arr) = @_;
my @top = sort $func @arr[0..$top-1];
for my $i ($top..$#arr) {
my $x = -1;
for (my $t = $#top; $t >= 0; $t--) {
local ($a, $b) = ($arr[$i], $top[$t]);
last if($func->() == 1);
$x = $t;
}
if($x != -1) {
splice(@top, $x, 0, $arr[$i]);
pop(@top);
}
}
return @top;
}
In reply to sort_top
by dada
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.