Last active
August 29, 2015 13:59
-
-
Save Bolinha1/10871510 to your computer and use it in GitHub Desktop.
Método de busca binária (binary search) em PHP
This file contains hidden or 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
| <?php | |
| function buscaBinaria($array, $e) | |
| { | |
| $n = count($array); | |
| $low = 0; | |
| $mid; | |
| $high = $n - 1; | |
| while($low <= $high) | |
| { | |
| $mid = (int)(($high - $low) / 2) + $low; | |
| if($array[$mid] > $e) | |
| $high = $mid - 1; | |
| elseif($array[$mid] < $e) | |
| $low = $mid + 1; | |
| else | |
| return (int)$mid; | |
| } | |
| return -1; | |
| } | |
| $arr = array(100, 200, 300, 400, 500); | |
| return var_dump(buscaBinaria($arr, 600)); // saída -1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment