Overview
?? The binary search method mainly solves the problem of "finding the specified number in a pile number". To apply a binary lookup method, this "pile number" must have a feature:
- stored in the array
- Orderly arrangement
So if you are using a linked list, you cannot apply a binary lookup method on it. (Ozone in the interview is asked what data structures can be used on the binary lookup method: arrays? Linked list? It does not matter whether the same element exists in the array if the order is ascending or descending. In general, however, we hope and assume that the arrays are ascending and that the elements in the array are different.
theory
See:
Http://www.cnblogs.com/ider/archive/2012/04/01/binary_search.html
Http://taop.marchtea.com/04.01.html
Recursive implementation binary lookup (PHP)
function re_binary_search($arr,$target,$height,$low =0){ if($height<$low||$arr[$low] >$target||$arr[$height] <$target){return-1; }$mid= Intval (($low+$height)/2);if($arr[$mid] >$target){//First half segment returnRe_binary_search ($arr,$target,$mid-1,$low); }if($arr[$mid] <$target){//second half segment returnRe_binary_search ($arr,$target,$height,$mid+1); }return $mid;}
non-recursive implementation binary lookup (PHP)
function binary_search($arr,$target){ $length= Count ($arr);if($length<=0||$arr[0] >$target||$arr[$length-1] <$target){return-1; }$low=0;$height=$length-1; while($low<=$height){$mid= (int) (($low+$height)/2);if($arr[$mid] >$target){$height=$mid-1; }Else if($arr[$mid] <$target){$low=$mid+1; }Else{return $mid; } }return-1;}
called
var_dump(re_binary_search($item,‘8‘,count($item)-1));var_dump($item[re_binary_search($item,‘8‘,count($item)-1)]);var_dump(binary_search($item,‘8‘));var_dump($item[binary_search($item,‘8‘)]);
Results
Binary Lookup algorithm