2 ms·
I wrote my version in PHP, wondering if someone could tell me what I did wrong (I didn't test it, I assume there are mistakes). <?php function bsearch($sea
by ohashi 17y ago
I wrote my version in PHP, wondering if someone could tell me what I did wrong (I didn't test it, I assume there are mistakes).
<?php
function bsearch($search, $array, $start, $end){
//$start cannot be zero.
//$search not in $array
if($start>$end){
return -1;
}
//calculate middle
$middle = $start + ceil(($end-$start)/2);
//check match
if($array[$middle]==$search){
return $middle;
}
//is the middle higher than the search, if so, cut top
else if($array[$middle]>$search){
return bsearch($search, $array, $start, $middle-1);
}
//otherwise cut bottom
else{
return bsearch($search, $array, $middle+1, $end);
}
}
?>
- gizmo 17y agoYup, no sigar. 1. You get a division by zero when $start == $end 2. When the element $search doesn't exist your program breaks 3. You always check array for value $middle, so $middle should have the range 0 <= $middle < length($array). But according to the comment $start cannot be zero. If so, then $middle is always larger than zero, and as such, the first element of the array is never considered. So it's pretty buggy.
- ohashi 17y ago1. i knew there was issue with start==end. what is the solution for that issue? i had originally written $start<=$end 2. i think this is connected to previous issue, with ending it 3. I knew the zero thing would be an issue, but... had to write it before caps game started :(