
japhy
Enthusiast
Sep 5, 2000, 7:50 AM
Post #7 of 7
(1419 views)
|
Re: Quick way to find biggest number of three?
[In reply to]
|
Can't Post
|
|
I think a non-hash solution is best. If you have a set of numbers, and you want the highest, then why not just use: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> @num = qw( 17 43 12 54 12 5 3 ); $wanted = highest(\@num); sub highest { my ($wanted,@_) = @{ $_[0] }; for (@_) { $wanted = $_ if $_ > $wanted } return $wanted; } </pre><HR></BLOCKQUOTE> This does N-1 comparisons for a list of N elements. My tests with sort() show less than favorable results: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> for ( [1,2,3,4], [1,2,4,3], [1,3,2,4], [1,3,4,2], [1,4,2,3], [1,4,3,2], [2,1,3,4], [2,1,4,3], [2,3,1,4], [2,3,4,1], [2,4,1,3], [2,4,3,1], [3,1,2,4], [3,1,4,2], [3,2,1,4], [3,2,4,1], [3,4,1,2], [3,4,2,1], [4,1,2,3], [4,1,3,2], [4,2,1,3], [4,2,3,1], [4,3,1,2], [4,3,2,1]) { sort { $j++, $b <=> $a } @$_; $count++; } printf "%d sets, %d cmp's, average: %.2f\n", $count, $j, $j/$count; </pre><HR></BLOCKQUOTE> 24 sets, 118 <=>'s, average: 4.92 The average is nearly 5, which is N+1. And only two cases had N-1 (3) comparisons. A hand-rolled solution might be the way to go. ------------------ Jeff "japhy" Pinyan -- accomplished author, consultant, hacker, and teacher
|