Assuming you have a sorted array of scores (it doesn't have to be 10 of them) with the highest first and the lowest last, you probably want to update the list in regards to a new score. Here's an efficient way to do it that doesn't use Perl's builtin sort(), and works in O(N) time.
sub crop_sort {
my ($a, $x) = @_;
if ($a->[-1] < $x) { $a->[-1] = $x }
else { return }
for (my $i = @$a - 2; $i >= 0; $i--) {
if ($a->[$i] < $a->[$i+1]) {
@$a[$i,$i+1] = @$a[$i+1,$i];
}
else { last }
}
}
I called it crop-sort even though it's just a one-pass bubble-sort because of its behavior. It effectively adds an element to the array and bubbles its way to the proper location, and then removes the least element. Except it does it a little smarter than that -- if the new element is smaller than any other, the function returns immediately. Otherwise, the l(e)ast element is replaced by the new element, and the bubbling occurs. This is at most O(N) time if the new element happens to be larger than all the others.
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.