python
# *_*coding:utf-8 *_*
def binaery_search(list,item):
low=0
high=len(list)-1
while low <= high:
mid=int((low+high)/2)
guess=list[mid]
if guess == item:
return mid
if guess >item:
high=mid-1
else:
low=mid+1
return None
my_list=[1,3,5,7,9,11]
print(binaery_search(my_list,1))
print(binaery_search(my_list,3))
print(binaery_search(my_list,5))
print(binaery_search(my_list,7))
print(binaery_search(my_list,9))
print(binaery_search(my_list,11))
print(binaery_search(my_list,-1))
php代码
<?php //二分查找法 function binSearch($arr,$search){ $height=count($arr)-1; $low=0; while($low<=$height){ $mid=floor(($low+$height)/2);//获取中间数 echo $mid; if($arr[$mid]==$search){ return $mid;//返回 }elseif($arr[$mid]<$search){//当中间值小于所查值时,则$mid左边的值都小于$search,此时要将$mid赋值给$low $low=$mid+1; }elseif($arr[$mid]>$search){//中间值大于所查值,则$mid右边的所有值都大于$search,此时要将$mid赋值给$height $height=$mid-1; } } return "查找失败"; } //二分查找递归实现 function binSearch2($arr,$low,$height,$k){ if($low<=$height){ $mid=floor(($low+$height)/2);//获取中间数 var_dump($low.$height); echo "<br>"; var_dump($mid); if($arr[$mid]==$k){ return $mid; }elseif($arr[$mid]<$k){ return binSearch2($arr,$mid+1,$height,$k); }elseif($arr[$mid]>$k){ return binSearch2($arr,$low,$mid-1,$k); } } return -1; } //顺序查找 function seqSearch($arr,$k){ foreach($arr as $key=>$val){ if($val==$k){ return $key; } } return -1; } $arr=array(1,2,3,4); $res = binSearch2($arr,0,4,4); var_dump($res);