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.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 } } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: crop-sort: Maintaining a Top-10 Array
by wog (Curate) on Nov 10, 2001 at 21:11 UTC | |
|
Re: crop-sort: Maintaining a Top-10 Array
by merlyn (Sage) on Nov 11, 2001 at 17:37 UTC | |
|
(tye)Re: crop-sort: Maintaining a Top-10 Array
by tye (Sage) on Nov 12, 2001 at 23:06 UTC |