我为二进制搜索编写了这段代码 但它有一些问题。有人可以帮我写更好的代码吗?
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);
致命错误:第15行的D:\ xampp \ htdocs \ bin2.php中允许的内存大小为1073741824字节(试图分配65488字节)
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
}
答案 0 :(得分:1)
问题是你必须施展
(($high-$low)/2)
到
的整数intval(($high-$low)/2)
同时致电
bs ($a,$val,$low,$mid--);
bs ($a,$val,$low,$mid++);
在函数调用后递减/递增$ mid ,所以你应该使用
bs ($a,$val,$low,$mid-1);
bs ($a,$val,$low,$mid+1);
此外,PHP代码与您在编写
时发布的伪代码不匹配return bs ($a,$val,$low,$mid+1);
应该是
return bs ($a,$val,$mid+1,$high);
最后我不认为
return print 'found';
return print 'not found';
将给出预期的行为:
return -1;
return $mid;
所以整个事情变成了
function bs ($a,$val,$low,$high){
if ($high < $low){
return -1;
}
$mid= $low + intval(($high-$low)/2);
if ($a[$mid]>$val){
return bs ($a,$val,$low,$mid-1);
}else if ($a[$mid]<$val){
return bs ($a,$val,$mid+1,$high);
}else{
return $mid;
}
}
$array=array(1,2,3,4,5,6,7);
$idx = bs ($array,5,0,6);
if($idx==-1)
{
echo 'not found';
}
else
{
echo 'Found at index' . $idx;
}
答案 1 :(得分:0)
$x = 101;
$a = array(-4,-1,5,7,12,35,56,98,101,124);
$n = count($a);
$low = 0;
$high = $n - 1;
while($low <= $high){
$mid = floor(($low + $high)/2);
if($x < $a[$mid]){
$high = $mid - 1;
}elseif($x > $a[$mid]){
$low = $mid + 1;
}else{
echo $a[$mid] . ' ' . $mid;
return;
}
}