Home >Backend Development >PHP Tutorial >这样写二分查找怎么不对呢

这样写二分查找怎么不对呢

WBOY
WBOYOriginal
2016-06-23 14:04:211334browse

<php function binarySearch($arr,$a){        $low = 0;    $high = count($arr)-1;    $mid = ceil(($low+$high)/2);while($low<=$high){    if($a==$arr[$mid]){    	echo "查找的数的位置是第"."$mid";    }    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);    }  }}$arr1 = array(5,7,9,10,12,16,19);binarySearch($arr1,12);?>


回复讨论(解决方案)

function binarySearch($arr,$a){
     
    $low = 0;
    $high = count($arr)-1;
    $mid = ceil(($low+$high)/2);
$n = 0;防止死循环的措施
while($low     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          
        $low = 0;
        $high = $mid +1; //注意这里
        $mid = ceil(($low+$high)/2);
    }
  }
}

按 php 实际可写作

function binarySearch($arr,$a){  $low = 0;  $high = count($arr)-1;  $mid = ceil(($low+$high)/2);  $num = count($arr);  while($low<=$high && $num--){    if($a==$arr[$mid]){      echo "查找的数的位置是第"."$mid";      break;    }    list($low, $high) = $a > $arr[$mid] ? array($mid, $high) : array($low, $mid);    $mid = ceil(($low+$high)/2);  }}

本帖最后由 xuzuning 于 2013-03-30 17:42:33 编辑
            function binarySearch($arr,$a){
     
    $low = 0;
    $high = count($arr)-1;
    $mid = ceil(($low+$high)/2);
$n = 0;防止死循环的措……  
我有点晕   如果是四个数呢,比如$r=array(1,2,3,4)  查找1 貌似不行        用floor来求$mid  这个  我  理解,用ceil貌似 有点问题、、、、   


按 php 实际可写作
PHP code?1234567891011121314function binarySearch($arr,$a){  $low = 0;  $high = count($arr)-1;  $mid = ceil(($low+$high)/2);  $num = count($arr);  while($low 还是要  谢谢 版主大大、、、

function binarySearch($arr,$a){  $low = 0;  $high = count($arr)-1;  $mid = ceil(($low+$high)/2);  $loop = count($arr);  while($low<$high-1 && $loop--){    if($a==$arr[$mid]){      echo "查找的数的位置是第"."$mid";      return $mid;    }    list($low, $high) = $a>$arr[$mid] ? array($mid, $high) : array($low, $mid);    $mid = ceil(($low+$high)/2);  }  echo "查找的数的位置在第{$low}、{$high}之间";}$arr1 = array(5,7,9,10,12,16,19);binarySearch($arr1,11);

Statement:
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