in reply to Binary search algorithm.


I modified your code slightly, to show the speed differences.

Relevant NYTProf output:

Line State
ments
Time
on line
Calls Time
in subs
Code
37112µsfor (1..100000) {
38100000928ms1000004.23s $result=BinSearch(\@a, \$w);
# spent 4.23s making 100000 calls to main::BinSearch, avg 42µs/call
391000001.46s100000728ms say $result;
# spent 728ms making 100000 calls to main::CORE:say, avg 7µs/call
401000001.43s ($result)=grep { $a$_ eq $w } 0..$#a;
411000001.65s100000673ms say $result;
# spent 673ms making 100000 calls to main::CORE:say, avg 7µs/call
42}

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
ments
Time
on line
Calls Time
in subs
Code
3811.66msfor (1..1000) {
39100024.1ms100014.4s $result=BinSearch(\@a, \$w);
# spent 14.4s making 1000 calls to main::BinSearch, avg 14.4ms/call
40100046.9ms100034.3ms say $result;
# spent 34.3ms making 1000 calls to main::CORE:say, avg 34µs/call
4110006.35s ($result)=grep { $a$_ eq $w } 0..$#a;
42100062.3ms100029.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

--
Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)

Replies are listed 'Best First'.
Re^2: Binary search algorithm.
by jwkrahn (Abbot) on Aug 13, 2011 at 05:33 UTC
    And finally, why don't you just use grep? At least with your trivial example, it is significantly faster.

    You are comparing apples to oranges.

    grep is always O( N ) and will work whether the data is sorted or not.

    Binary Search has a best case of O( 1 ) and a worst case of O( log N ) and will only work if the data is sorted.

      Actually, you are. The formula you are giving says how the speed of the algorithms *scale*, whereas afoken was talking about how fast they are.

      Although you do bring up a good point: afoken only measured the worst case.