Created
November 25, 2024 15:04
-
-
Save daler445/e76405a9ebc2164377469e1db4f9f987 to your computer and use it in GitHub Desktop.
Binary search
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
/** | |
* @param Integer[] $nums | |
* @param Integer $target | |
* @return Integer | |
*/ | |
function search(array $nums, int $target): int { | |
$left = 0; | |
$right = count($nums) - 1; | |
while ($left <= $right) { | |
$middle = $left + (($right - $left) / 2); | |
$middle = (int)$middle; | |
if ($nums[$middle] === $target) { | |
return $middle; | |
} | |
if ($target < $nums[$middle]) { | |
$right = $middle - 1; | |
} else { | |
$left = $middle + 1; | |
} | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment