二分法查找的思路如下:
1、首先,从数组的中间元素开始搜索,如果该元素正好是目标元素,则搜索过程结束,否则执行下一步。
2、如果目标元素大于/小于中间元素,则在数组大于/小于中间元素的那一半区域查找,然后重复步骤(1)的操作。
3、如果某一步数组为空,则表示找不到目标元素。
php版:
<?php
function binarySearch($array, $val) {
$count = count($array);
$low = 0;
$high = $count - 1;
while ($low <= $high) {
$mid = intval(($low + $high) / 2);
if ($array[$mid] == $val) {
return $mid;
}
if ($array[$mid] < $val) {
$low = $mid + 1;
} else {
$high = $mid - 1;
}
}
return false;
}
python3版:
def binary_search(list,item):#list必须是按从小到大排好序的序列
low=0
height=len(list)-1
while low <= height:
mid=(low+height)//2
#print(mid)
guess=list[mid]
if guess==item:
return mid
if guess < item:
low=mid+1
else:
height=mid-1
return None
print(binary_search([1,2,3,4,5],4))