1 <?php 2 3 //通过 4 function bin_search($a_data, $key) 5 { 6 $len = count($a_data); 7 $low = 0; 8 $high = $len - 1; 9 while ($low <= $high) { 10 $mid = intval(($high + $low) / 2); 11 if ($key < $a_data[$mid]) { 12 $high = $mid - 1; 13 } elseif ($key > $a_data[$mid]) { 14 $low = $mid + 1; 15 } else { 16 return true; 17 } 18 } 19 20 return false; 21 } 22 23 //通过 24 //递归版本 25 function bin_search_recurse($a_data, $low, $high, $key) 26 { 27 if ($low <= $high) { 28 $mid = intval(($low + $high) / 2); 29 if($a_data[$mid] == $key) { 30 return true; 31 } elseif ($key < $a_data[$mid]) { 32 return bin_search_recurse($a_data, $low, $mid - 1, $key); 33 } else { 34 return bin_search_recurse($a_data, $mid + 1, $high, $key); 35 } 36 } 37 38 return false; 39 } 40 41 $a_data = [1,2,3,4,5,6,7,8,9]; 42 var_dump(bin_search_recurse($a_data, 0, count($a_data) - 1, 30)); 43