Skip to content

Instantly share code, notes, and snippets.

@fajarwz
Created November 19, 2023 06:51
Show Gist options
  • Save fajarwz/2446d22013077666f744e019f5f4eedb to your computer and use it in GitHub Desktop.
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
<?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