PHP Binary Lookup-recursive vs. non-recursive sample code sharing
<?phpfunction BinarySearch ($arr, $val) {$len = count ($arr); if (!is_array ($arr) | | $len <= 0) {return false;} if ($val < $arr [0] | | $val > $arr [$len-1]) {return false;} $start = 0; $end = $len -1;while ($start <= $end) {$mid = Intval (($end + $start)/2);//Intermediate value if ($arr [$mid] = = $val) {return $ Mid;} if ($val < $arr [$mid]) {$end = $mid-1;} else{$start = $mid + 1;}} return false;}
Recursive implementations:
<?php//recursive function Binarysearch_r ($arr, $low, $high, $key) {$len = count ($arr); if (!is_array ($arr) | | $len <= 0) {return false;} if ($key < $arr [0] | | $key > $arr [$len-1]) {return false;} if ($low <= $high) {$mid = Intval (($low + $high)/2), if ($arr [$mid] = = $key) {return true;} $func _name = function;if ($key < $arr [$mid]) {return $func _name ($arr, $low, $mid-1, $key);} Else{return $func _name ($arr, $mid +1, $high, $key);}} return false;}