Home >Backend Development >PHP Tutorial >PHP二分查找的困惑

PHP二分查找的困惑

WBOY
WBOYOriginal
2016-06-13 12:15:101059browse

PHP二分查找的疑惑
$Arr=array(1,3,4,5,7,8,9);
Search($Arr,7,0,count($Arr)-1);
function Search($Arr,$FindVal,$LeftIndex,$RightIndex){
if($FindVal>$Arr[count($Arr)-1]){
echo "找不到该值";
}else if($FindValecho "找不到该值";
}else{
$MiddleIndex=round(($LeftIndex+$RightIndex)/2);
if ($Arr[$MiddleIndex]Search($Arr,$FindVal,++$MiddleIndex,$RightIndex);
}else if($Arr[$MiddleIndex]>$FindVal){
Search($Arr,$FindVal,$LeftIndex,--$MiddleIndex);
}else{
echo "找到下标为$MiddleIndex";
}
}
}

请问下各位朋友,这段代码执行下来,是不是执行了好几个函数。有朋友能深入讲解下时序图吗? 谢谢,感激不尽。
------解决思路----------------------

$Arr = array(1,3,4,5,7,8,9);<br />Search($Arr,7,0,count($Arr)-1);<br /><br />function Search($Arr,$FindVal,$LeftIndex,$RightIndex){<br />  echo "$FindVal,$LeftIndex,$RightIndex\n"; //加上这句<br />  if($FindVal>$Arr[count($Arr)-1]){<br />    echo "找不到该值";<br />  }else if($FindVal<$Arr[0]){<br />    echo "找不到该值";<br />  }else{<br />    $MiddleIndex=round(($LeftIndex+$RightIndex)/2);<br />    if ($Arr[$MiddleIndex]<$FindVal){<br />      Search($Arr,$FindVal,++$MiddleIndex,$RightIndex);<br />    }else if($Arr[$MiddleIndex]>$FindVal){<br />      Search($Arr,$FindVal,$LeftIndex,--$MiddleIndex);<br />    }else{<br />      echo "找到下标为$MiddleIndex";<br />    }<br />  }<br />}
7,0,6
7,4,6
7,4,4
找到下标为4

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