日期:2014-05-17 浏览次数:20519 次
<?php $arr = array(1,2,3,4,5,6,7,8,9); print_r(binarySearch($arr,9)); function binarySearch($arr,$Num){ $StartPos=0; $EndPos = count($arr)-1; $m = (int)(($EndPos+$StartPos)/2); while($arr[$m]!=$Num){ if($arr[$m] == $Num){ break; }else if($arr[$m] < $Num){ $StartPos = (int)$m; if($m+$EndPos>(2*$m)){ $m= (int)(($m+$EndPos)/2)+1; } }else if($arr[$m] > $Num){ $EndPos = (int)$m; $m= (int)(($m+$StartPos)/2); } } return $m; } ?>