Created
November 19, 2023 06:51
-
-
Save fajarwz/2446d22013077666f744e019f5f4eedb to your computer and use it in GitHub Desktop.
search for a value in a sorted array using Binary Search, the best searching algorithm for a sorted array
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
<?php | |
function binarySearch($arr, $target) { | |
$left = 0; | |
$right = count($arr) - 1; | |
while ($left <= $right) { | |
$mid = floor(($left + $right) / 2); | |
// Check if the target is present at the middle | |
if ($arr[$mid] == $target) { | |
return $mid; | |
} | |
// If the target is greater, ignore the left half | |
if ($arr[$mid] < $target) { | |
$left = $mid + 1; | |
} | |
// If the target is smaller, ignore the right half | |
else { | |
$right = $mid - 1; | |
} | |
} | |
// If we reach here, then the element was not present | |
return -1; | |
} | |
// Example usage | |
$sortedArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; | |
$targetValue = 5; | |
echo binarySearch($sortedArray, $targetValue); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment