二分法查找数组是否包含某一元素,兼容正反序,代码实现:
复制代码 代码如下:
$searchValue = (int)$_GET['key'];
function search(array $array, $value)
{
$max = count($array)-1;
$min = 0;
$isAscSort = $array[$min]
while (TRUE) {
$sum = $min+$max;
$midKey = (int)($sum%2 == 1 ? ceil($sum/2) : $sum/2);
if ($max return -1;
} else if ($value == $array[$midKey]) {
return 1;
} else if ($value > $array[$midKey]) {
$isAscSort ? $min = $midKey+1 : $max = $midKey-1;
} else if ($value $isAscSort ? $max = $midKey-1 : $min = $midKey+1;
}
}
}
$array = array(
'4', '5', '7', '8', '9', '10', '11', '12'
);
// 正序
echo search($array, $searchValue);
// 逆序
rsort($array);
echo search($array, $searchValue);