//有一个数组 {1,2,3,4,5,6,7,8,9,12,13,45,67,89,99,101,111,123,134,565,677} 查找数组中是否有指定的某一个数.
/**
*----------------------------------------
* Time:2016-06-21 | 二分查找
*---------------------------------------
*/
function binarySearch(&$arr,$findVal,$leftIndex,$rightIndex){
if($rightIndex < $leftIndex){
echo "哇哇哇,找不到o(︶︿︶)o 唉";
return;
}
// @ 取中间的key
$middleIndex=round(($rightIndex+$leftIndex)/2);
if($findVal > $arr[$middleIndex]){
binarySearch($arr,$findVal,$middleIndex+1,$rightIndex);
}else if($findVal < $arr[$middleIndex]){
binarySearch($arr,$findVal,$leftIndex,$middleIndex-1);
}else{
echo "哇哇哇找到你了o(∩_∩)o 哈哈。下标是$middleIndex";
}
}
$arr=array(1,2,3,4,5,6,7,8,9,12,13,45,67,89,99,101,111,123,134,565,677);
print_r(binarySearch($arr,89,0,count($arr)-1));