Re: [问题] 判断一数字是否介于某些范围之内

楼主: AchieveDream (AchieveDream)   2015-06-14 03:28:57
※ 引述《red0whale (red whale)》之铭言:
: 假设我有一阵列变量$a=[2,7,14,28,32,38,41,49];
: 今假设一个数$b
: 请问怎么判断$b是否介于2~7、14~28、32~38、41~49这些范围之内?
: (亦即$b是否介于$a的数值范围内,假设$a有偶数个元素)
觉得题目满有趣的,因此尝试一下,这也是我第一次PO文~
function is_in_range(array $range = [], $search)
{
$high = count($range) - 1;
if ((-1 === $high) || 0 === ($high & 1))
{
return false;
}
$low = 0;
$search = intval($search);
while ($low <= $high)
{
$mid = (($low + $high) >> 1);
if ($search === $range[$mid])
{
return true;
}
else if ($search > $range[$mid])
{
if ($mid === $high)
{
return false;
}
else if ((0 === ($mid & 1)) && ($search < $range[$mid+1]))
{
return true;
}
$low = $mid + 1;
}
else
{
if ($mid === $low)
{
return false;
}
else if ((1 === ($mid & 1)) && ($search > $range[$mid-1]))
{
return true;
}
$high = $mid - 1;
}
}
return false;
}

Links booklink

Contact Us: admin [ a t ] ucptt.com