1 <?php
2 #二分查找
3 function binarySearch(Array $arr, $target) {
4 $low = 0;
5 $high = count($arr) - 1;
6
7 while($low <= $high) {
8 $mid = floor(($low + $high) / 2);
9 #找到元素
10 if($arr[$mid] == $target) return $mid;
11 #中元素比目标大,查找左部
12 if($arr[$mid] > $target) $high = $mid - 1;
13 #重元素比目标小,查找右部
14 if($arr[$mid] < $target) $low = $mid + 1;
15 }
16
17 #查找失败
18 return false;
19 }
20
21 $arr = array(1, 3, 5, 7, 9, 11);
22 $inx = binarySearch($arr, 1);
23 var_dump($inx);
24 ?>