in reply to Re: Re: *Fastest* way to print a hash sorted by value
in thread *Fastest* way to print a hash sorted by value
Feel free to "optimize" it.
He's gonna need some optimisations, or War & peace:)
The problem with this method is that you have to re-sort the keep array every time you add a new key.
If you are keeping the top 100 elements from 10_000_000, you are going to be sorting the 100 element array 9_999_901 times. Even with the existing 100 elements being already sorted, and despite 5.8's default mergesort and its ability to "takes advantage of pre-existing order", adding a single value to a pre-sorted array of one hundred elements, still seems to take an average of around 120 calls to the comparator.
use sort ''; print sort::current; mergesort @array = 1..99; $c=0; @b = sort{ $c++; $a <=> $b } @array, 0; print $c 113; $c=0; @b = sort{ $c++; $a <=> $b } @array, 100; print $c 99; $c=0; @b = sort{ $c++; $a <=> $b } @array, 50; print $c 127 $c=0; @b = sort{ $c++; $a <=> $b } @array, 49; print $c 127 $c=0; @b = sort{ $c++; $a <=> $b } @array, 75; print $c 127 $c=0; @b = sort{ $c++; $a <=> $b } @array, 12; print $c 122
I think this falls into tyes second category.
Using a binary chop to locate the insertion point will take at most 8 comparisons and an average of 5. Add a couple of pre-comparisons to save doing the chop when the element to be added is less than the smallest to date, or greater than the largest, and you can avoid needing to do the binary chop much of the time.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Re: Re: *Fastest* way to print a hash sorted by value
by bart (Canon) on Aug 09, 2003 at 22:31 UTC | |
by BrowserUk (Patriarch) on Aug 10, 2003 at 10:33 UTC |