in reply to Speed up my code
but its taking some time to finish this task.
It won't make any discernible difference on such a small dataset as your sample, but avoiding the sort for much larger datasets should be a win:
#! perl -slw use strict; my %hash; ++$hash{ <> } until eof(); my @top5; for( keys %hash ) { for my $i ( 0 .. 4 ) { if( !defined( $top5[ $i ] ) or $hash{ $_ } > $hash{ $top5[ $i +] } ) { splice @top5, $i, 0, $_; pop @top5 if @top5 > 5;; last; } } } print @top5; __END__ many hardships a million dollars love life apple pie you attempt things
Note: the difference between my output and your expected is due to there being no clear winner for 5th place.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Speed up my code
by Tux (Canon) on Dec 14, 2011 at 14:50 UTC | |
|
Re^2: Speed up my code
by BrowserUk (Patriarch) on Dec 14, 2011 at 14:54 UTC |