I am employing a binary search over a fairly large (~1-10Million integers) sorted array. My perl code, which is given below,
(1) returns the index of the array if it finds a match
(2a) if it does NOT find a match and begin=1, returns the index of the array where the "search query must belong"
(2b) if it does NOT find a match and begin=0, returns the index of the array where the "search query must belong" minus 1
I call this subroutine ~400 times, and it takes about 7 minutes. I have no clue why it is taking so long. My colleague who has this subroutine written in python runs is no time. Is Perl's long running time due to the way Perl handles arrays?
Can you please suggest what is wrong with the code, and provide tips to speed-up?
Thanks a lot in advance
sub binarySearch ### sample call: $returnValue = binarySearch($begin
+, $query, \@ArrayPtr);
{
my ($begin, $query, $ArrayPtr); ### begin = 1 or 0
($begin, $query, $ArrayPtr) = @_;
my(@array) = @$ArrayPtr;
### Handling cases when query is out of bounds
return 0 if ($query < $array[0] && $begin == 1);
return $#array if ($query > $array[$#array] && $begin == 0);
my ($left) = 0;
my ($right) = $#array;
my ($center);
my ($prevCenter) = -1;
while(1)
{
$center = int (($left + $right)/2 );
if ($query == $array[$center])
{
if ($begin == 1)
{
while($center > 0 && $array[$center] == $array[$center-1])
{ $center = $center - 1; }
}
else
{
while($center < $#array && $array[$center] == $array[$center+1
+])
{ $center = $center + 1; }
}
undef @array;
return $center;
}
if ($center == $prevCenter)
{
undef @array;
return $right if ($begin == 1);
return $right-1 if ($begin == 0);
}
$right = $center if ($query < $array[$center]);
$left = $center if ($query > $array[$center]);
$prevCenter = $center;
}
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.