Instantly share code, notes, and snippets.

Embed
What would you like to do?
Простой бинарный поиск
function binary_search($list, $item) {
$min = 0;
$max = count($list)-1;
while($min <= $max) {
$middle = round(($min+$max)/2);
$guess = $list[$middle];
if($guess === $item) {
return 'index - ' .$middle . ', value -' . $item;
} elseif ($guess > $item) {
$max = $middle - 1;
} elseif($guess < $item) {
$min = $middle + 1;
}
}
return null;
}
var_dump(binary_search(array(1, 3, 5, 6, 8, 9, 10, 90), 5));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment