In some cases, there is an already ordered array, if you want to get a number in the order of the array, using the traversal method will be slower, as follows is a quick get position of the function, will return: In this array, how many values are smaller than the given value.
#!/usr/bin/env Perl UseStrict; Usewarnings;my @array=(1,2,2,3,4,5,6,7,8,9,Ten);my $value=Shift;@array=Sort{$a<=>$b}@array;my $percent=&findless ($value,@array);Print "$percent \ n";Subfindless{my($value,@array)=@_; my $result=-1; my $array _length=@array; my $left=0; my $right=$array _length-1; while(1){ if($value<=$array[$left]){ $result=$left; } elsif($value>$array[$right]){ $result=$right+1; } elsif($right-$left<=1){ if($value>$array[$left]){ $result=$left+1; } Else{ $result=$left; } } Else{ my $mid=int(($left+$right)/2); #print "mid\t$mid\n"; if($value<=$array[$mid]){ $right=$mid; } Else{ $left=$mid; } #print "$left \t$right\n"; } Last if($result>=0); } #print "$result \ n"; my $percent=($result)/$array _length; return($percent);}
Perl Quick get the sort of numbers in the array