二分法查找
2016-01-25 PHP 761
header(\'Content-Type: text/html; charset=utf-8;\');
$arr = array(2,33,22,1,323,321,28,36,90,123);
sort($arr);
//二分法查找
echo $index = binarySearch($arr,321);
function binarySearch($arr,$
header('Content-Type: text/html; charset=utf-8;'); $arr = array(2,33,22,1,323,321,28,36,90,123); sort($arr); //二分法查找 echo $index = binarySearch($arr,321); function binarySearch($arr,$key){ $len = count($arr); $mid = -1; $start = 0; $end = $len-1; while($start<=$end){ $mid = (int)(($start+$end)/2); echo $mid."\n"; if($arr[$mid] == $key){ return $mid; }else if($arr[$mid] < $key){ $start = $mid+1; }else if($arr[$mid] > $key){ $end = $mid-1; } } }
很赞哦! (0)
相关文章
文章评论
-
-
-
0条评论