1.PHP实现二分查找
#二分查找 function binarySearch(Array $arr, $target) { $low = 0; $high = count($arr) - 1; while($low <= $high) { $mid = floor(($low + $high) / 2); #找到元素 if($arr[$mid] == $target) return $mid; #中元素比目标大,查找左部 if($arr[$mid] > $target) $high = $mid - 1; #重元素比目标小,查找右部 if($arr[$mid] < $target) $low = $mid + 1; } #查找失败 return false; } $arr = array(1, 3, 5, 7, 9, 11); $inx = binarySearch($arr, 1); var_dump($inx); 2.PHP实现顺序查找 function search($array, $k){ $n = count($array); $array[$n] = $k; for($i=0; $i<$n; $i++) { if($array[$i]==$k) { return $i; break; } } return -1; }$array = array(5,6,3,7,11,61);echo search($array, 11);