I wrote this code for a binary search but it has some problems. Can someone help me write better code?
function bs ($a,$val,$low,$high){
if ($high < $low){
return print "not found";
}
$mid= $low + (($high-$low)/2);
if ($a[$mid]>$val){
return bs ($a,$val,$low,$mid--);
}else if ($a[$mid]<$val){
return bs ($a,$val,$low,$mid++);
}else{
return print 'found';
}
}
$array=array(1,2,3,4,5,6,7);
bs ($array,5,0,6);
Problem
Fatal error: Allowed memory size of 1073741824 bytes exhausted (tried to allocate 65488 bytes) in D:\xampp\htdocs\bin2.php on line 15
BinarySearch(A[0..N-1], value, low, high) {
if (high < low)
return -1 // not found
mid = low + ((high - low) / 2) // Note: not (low + high) / 2 !!
if (A[mid] > value)
return BinarySearch(A, value, low, mid-1)
else if (A[mid] < value)
return BinarySearch(A, value, mid+1, high)
else
return mid // found
}
but have some problem-- How are we supposed to know what the problem is if you don't tell us? What doesn't work? What are the expected results and what did you get instead?2.5, then becomes 2.25, 2.125 etc... and you never ever stop recursing.