"my" variable $lo masks earlier declaration in same scope at foo.pl li +ne 14. "my" variable $hi masks earlier declaration in same scope at foo.pl li +ne 14. "my" variable @array masks earlier declaration in same scope at foo.pl + line 21. "my" variable $try masks earlier declaration in same scope at foo.pl l +ine 21. "my" variable $word masks earlier declaration in same scope at foo.pl +line 21. "my" variable @a masks earlier declaration in same scope at foo.pl lin +e 33. syntax error at foo.pl line 12, near "<= :" syntax error at foo.pl line 30, near "}" Execution of foo.pl aborted due to compilation errors.
Untested, right? After removing the obvious vi command in line 12, I still get
"my" variable @a masks earlier declaration in same scope at foo.pl lin +e 32.
Please don't post untested code.
I modified your code slightly, to show the speed differences.
Relevant NYTProf output:
Line State
mentsTime
on lineCalls Time
in subsCode 37 1 12µs for (1..100000) { 38 100000 928ms 100000 4.23s $result=BinSearch(\@a, \$w); # spent 4.23s making 100000 calls to main::BinSearch, avg 42µs/call39 100000 1.46s 100000 728ms say $result; # spent 728ms making 100000 calls to main::CORE:say, avg 7µs/call40 100000 1.43s ($result)=grep { $a$_ eq $w } 0..$#a; 41 100000 1.65s 100000 673ms say $result; # spent 673ms making 100000 calls to main::CORE:say, avg 7µs/call42 }
Modified code:
my @a = qw(format type ascii hex pos len binary search perl unix eof a +rray word); @a = sort @a; my $w = "len"; say "@a"; my $result; open STDOUT,'>','/dev/null'; for (1..100000) { $result=BinSearch(\@a, \$w); say $result; ($result)=grep { $a[$_] eq $w } 0..$#a; say $result; }
Even with 10,000 pieces of junk in front of the searched element, grep still beats your BinSearch easily:
Relevant NYTProf output:
Line State
mentsTime
on lineCalls Time
in subsCode 38 1 1.66ms for (1..1000) { 39 1000 24.1ms 1000 14.4s $result=BinSearch(\@a, \$w); # spent 14.4s making 1000 calls to main::BinSearch, avg 14.4ms/call40 1000 46.9ms 1000 34.3ms say $result; # spent 34.3ms making 1000 calls to main::CORE:say, avg 34µs/call41 1000 6.35s ($result)=grep { $a$_ eq $w } 0..$#a; 42 1000 62.3ms 1000 29.4ms say $result; # spent 29.4ms making 1000 calls to main::CORE:say, avg 29µs/call
Modified code:
my @a = ('00junk') x 10000; push @a,qw(format type ascii hex pos len binary search perl unix eof a +rray word); @a = sort @a; my $w = "len"; say "@a"; my $result; open STDOUT,'>','/dev/null'; for (1..1000) { $result=BinSearch(\@a, \$w); say $result; ($result)=grep { $a[$_] eq $w } 0..$#a; say $result; }
Alexander
In reply to Re: Binary search algorithm.
by afoken
in thread Binary search algorithm.
by kindlychung
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |