Created
March 13, 2018 20:40
-
-
Save al5dy/53355d863b56c9e55487d8dd040c67fd to your computer and use it in GitHub Desktop.
Простой бинарный поиск
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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