Skip to content

Instantly share code, notes, and snippets.

@al5dy
Created March 13, 2018 20:40
Show Gist options
  • Save al5dy/53355d863b56c9e55487d8dd040c67fd to your computer and use it in GitHub Desktop.
Save al5dy/53355d863b56c9e55487d8dd040c67fd to your computer and use it in GitHub Desktop.
Простой бинарный поиск
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