这样写二分查找怎么不对呢
<br />
<php <br />
function binarySearch($arr,$a){<br />
<br />
$low = 0;<br />
$high = count($arr)-1;<br />
$mid = ceil(($low+$high)/2);<br />
<br />
while($low<=$high){<br />
<br />
if($a==$arr[$mid]){<br />
echo "查找的数的位置是第"."$mid";<br />
}<br />
<br />
if($a>$arr[$mid]){<br />
<br />
$high = count($arr)-1;<br />
$low = $mid+1;<br />
$mid = ceil(($low+$high)/2);<br />
}<br />
<br />
if ($a<$arr[$mid]) {<br />
<br />
$low = 0;<br />
$high = $mid-1;<br />
$mid = ceil(($low+$high)/2);<br />
}<br />
}<br />
}<br />
$arr1 = array(5,7,9,10,12,16,19);<br />
binarySearch($arr1,12);<br />
<br />
?>
Copy after login
------解决方案--------------------本帖最后由 xuzuning 于 2013-03-30 17:42:33 编辑
function binarySearch($arr,$a){
$low = 0;
$high = count($arr)-1;
$mid = ceil(($low+$high)/2);
$n = 0;防止死循环的措施
while($low<=$high
&& $n++){
if($a==$arr[$mid]){
echo "查找的数的位置是第"."$mid";
break;
}
if($a>$arr[$mid]){
$high = count($arr)-1;
$low = $mid-1;//注意这里
$mid = ceil(($low+$high)/2);
}
if ($a<$arr[$mid]) {
$low = 0;
$high = $mid+1;//注意这里
$mid = ceil(($low+$high)/2);
}
}
}
------解决方案--------------------
按 php 实际可写作
function binarySearch($arr,$a){<br />
$low = 0;<br />
$high = count($arr)-1;<br />
$mid = ceil(($low+$high)/2);<br />
$num = count($arr);<br />
while($low<=$high && $num--){<br />
if($a==$arr[$mid]){<br />
echo "查找的数的位置是第"."$mid";<br />
break;<br />
}<br />
list($low, $high) = $a > $arr[$mid] ? array($mid, $high) : array($low, $mid);<br />
$mid = ceil(($low+$high)/2);<br />
}<br />
}<br />
Copy after login
------解决方案--------------------
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
-
2024-10-22 09:46:29
-
2024-10-13 13:53:41
-
2024-10-12 12:15:51
-
2024-10-11 22:47:31
-
2024-10-11 19:36:51
-
2024-10-11 15:50:41
-
2024-10-11 15:07:41
-
2024-10-11 14:21:21
-
2024-10-11 12:59:11
-
2024-10-11 12:17:31