方法一:函数法
二分查找描述:
此数组为有序数组
每次查找都要有中间值($mid = floor($start+$end)/2)
若要找的值恰好与中间的值相等就返回true,若要找的值比中间的值大,调整$start = $mid + 1($mid+1是因为$mid已经比较过了),若要找的值比中间的值小,调整$end = $mid - 1;
这函数为递归调用函数(要求大的方面先一层层调用小一级的,相同的方面,直到有已知的数值,再把结果一层层反推到要求的值)
<?php //用函数法求二分查找 $arr = array(1,2,3,4,5,6,7); $len = count($arr); $search = 9; $start = 0; $end = $len - 1; $result = binary_search($arr,$search,$start,$end); echo "最后结果为:";var_dump($result); function binary_search($arr,$search,$start,$end) { if($start > $end) { return false; } $mid = floor(($start + $end) / 2); if($arr[$mid] == $search) { return true; } else if($search > $arr[$mid]) { $temp = binary_search($arr,$search,$mid + 1,$end); return $temp; }else { $temp = binary_search($arr,$search,$start,$mid - 1); return $temp; } } ?>
方法二:直接法
$arr = array(1,2,3,4,5,6,7); $len = count($arr); $search = 7; $start = 0; $end = $len - 1; $flag = false;//标志位(来判断是否找到数) $mid = floor(($start + $end) / 2); while($start <= $end)//当$start > $end为判断假,退出循环 { if($arr[$mid] == $search) { $flag = true; break; }else if($arr[$mid] > $search) { $end = $mid - 1; $mid = floor(($start + $end) / 2); }else { $start = $mid + 1; $mid = floor(($start + $end) / 2); } } echo "结果为";var_dump($flag); ?>