PHP二分查找的简单实现
function sequential_search($list, $item)
{
foreach ($list as $key => $value) {
if ($value == $item) {
return $key;
}
}
return null;
}
function binary_search($list, $item)
{
$low = 0;
$high = count($list);
while ($low <= $high) {
$mid = floor(($low + $high) / 2);
$guess = $list[$mid];
if ($guess == $item) {
return $mid;
}
if ($guess > $item) {
$high = $mid - 1;
} else {
$low = $mid + 1;
}
}
return null;
}
$my_list = [1, 3, 5, 7, 9];
echo sequential_search($my_list, 9).'<br/>';
echo binary_search($my_list, 9);