F
Fatted
Is there a better (faster) way of implementing my top_sort function?
(Creating a top 10 list of the highest numbers from a large set).
Or did I get lucky?
--
#!/usr/bin/perl
use strict;
use warnings;
my @top10 = (0,0,0,0,0,0,0,0,0,0);
for(my $i = 0;$i < 10000; $i++)
{
my $num = rand();
@top10 = @{top_sort(\@top10, $num)};
}
# PRINT RESULTS
foreach (@top10)
{
print $_."\n";
}
sub top_sort
{
my $array = shift;
my $val = shift;
my @top;
# IF THE VALUE IS LESS THAN THE LAST VALUE IN THE TOP LIST,
# NO PROCESSING REQUIRED
if(defined($val) && $val >= 0)
{
if($val < $array->[$#$array])
{
return($array);
}
}
for(my $i = 0; $i < $#$array; ++$i)
{
if($val > $array->[$i])
{
# MAKE NEW TOP10 BY TAKING HIGHER MATCHES PLUS
THE NEW
# VALUE, PLUS THE LOWER MATCHES UP TO THE LIMIT
OF THE
# ARRAY.
@top = @$array[0..($i-1)];
push(@top, $val);
push(@top, @$array[$i..($#$array-1)]);
last;
}
}
# IN CASE OF PROBLEMS
if(!defined($top[0]))
{
@top = @$array;
}
return(\@top);
}
(Creating a top 10 list of the highest numbers from a large set).
Or did I get lucky?
--
#!/usr/bin/perl
use strict;
use warnings;
my @top10 = (0,0,0,0,0,0,0,0,0,0);
for(my $i = 0;$i < 10000; $i++)
{
my $num = rand();
@top10 = @{top_sort(\@top10, $num)};
}
# PRINT RESULTS
foreach (@top10)
{
print $_."\n";
}
sub top_sort
{
my $array = shift;
my $val = shift;
my @top;
# IF THE VALUE IS LESS THAN THE LAST VALUE IN THE TOP LIST,
# NO PROCESSING REQUIRED
if(defined($val) && $val >= 0)
{
if($val < $array->[$#$array])
{
return($array);
}
}
for(my $i = 0; $i < $#$array; ++$i)
{
if($val > $array->[$i])
{
# MAKE NEW TOP10 BY TAKING HIGHER MATCHES PLUS
THE NEW
# VALUE, PLUS THE LOWER MATCHES UP TO THE LIMIT
OF THE
# ARRAY.
@top = @$array[0..($i-1)];
push(@top, $val);
push(@top, @$array[$i..($#$array-1)]);
last;
}
}
# IN CASE OF PROBLEMS
if(!defined($top[0]))
{
@top = @$array;
}
return(\@top);
}