<?php/**二分查找:查找一个值在数组中的位置* @$arr:操作的数组,前提是按顺序排列* @$val:查找的值* @$low:查找的起始位置,默认从数组的第一个数找起* @hight:查找的结束位置**/function
binarySearch($arr,$val,$hight,$low=0){ while($low<=$hight){ $mid=ceil($low+
($hight-
$low) / 2); if($arr[$mid]
== $val){ return$mid; }elseif($arr[$mid]
> $val){ $hight=$mid
-1; }else{ $low=$mid
+1; } } return-1;}header('Content-Type:text/html; charset=utf-8');//产生一个数组$arr
= range(0,20);echo
'<pre>';print_r($arr);echo
'</pre>';$low
= 0;$hight
= count($arr) - 1;$findVal= rand(0, 20);$index
= findIndex($arr,$findVal,$hight,
$low);printf("查找的值 '%d' 在数组中的下标 '%s'",$findVal,$index);?> |
php二分查找法实例
最新推荐文章于 2021-10-27 22:17:26 发布
368

被折叠的 条评论
为什么被折叠?



