Binary search is a super efficient way to find an item in a sorted list. Instead of checking every single item one by one, it splits the list in half repeatedly until it finds what you are looking for.
Think of it like looking up a word in a dictionary: you open it to the middle, decide if your word is earlier or later, and then repeat the process with the correct half.
How it works:
1. Find the middle element of the array.
2. If the middle element matches your target, you’re done!
3. If the target is smaller, repeat the process on the left half.
4. If the target is larger, repeat the process on the right half.
function binarySearch(array $array, int $target): ?int {
$low = 0;
$high = count($array) - 1;
while ($low <= $high) {
// Use the middle index
$mid = $low + intdiv($high - $low, 2);
if ($array[$mid] === $target) {
return $mid;
}
if ($array[$mid] < $target) {
$low = $mid + 1;
} else {
$high = $mid - 1;
}
}
return null;
}
// Example usage:
$data = [10, 22, 35, 47, 50, 68, 75];
$result = binarySearch($data, 47);
echo ($result !== null) ? "Found at index: $result" : "Value not found.";