标签:
/** * Created by PhpStorm. * User: huangye * Date: 2015/8/26 * Time: 18:57 */ //通过 function binSearch_1($a_data, $key) { $len = count($a_data); $low = 0; $high = $len - 1; while ($low <= $high) { $mid = intval(($high + $low) / 2); if ($key < $a_data[$mid]) { $high = $mid - 1; } elseif ($key > $a_data[$mid]) { $low = $mid + 1; } else { return true; } } return false; } //通过 //递归版本 function binSearchRecurse($array, $low, $high, $k) { if ($low <= $high) { $mid = intval(($low + $high) / 2); if($array[$mid] == $k) { return true; } elseif ($k < $array[$mid]) { return binSearch_2($array, $low, $mid - 1, $k); } else { return binSearch_2($array, $mid + 1, $high, $k); } } return false; } $a_data = [1,2,3,4,5,6,7,8,9]; var_dump(binSearch_2($a_data, 0, count($a_data), 8));
标签:
原文地址:http://www.cnblogs.com/huangye-dream/p/4991423.html