Binary search (also known as half-interval search) is an efficient algorithm for locating a target element within an ordered array. It repeatedly divides the array into two halves, compares the target value with the middle element, and progressively narrows the search range until the target is found or confirmed absent.
The core steps of binary search include:
1. Set the start position of the array as left and the end position as right.
2. Calculate the middle position mid = (left + right) / 2.
3. Compare the target value with the element at the middle position:
4. Repeat these steps until the target is found or left > right, indicating search failure.
The following PHP code implements the binary search algorithm:
function binarySearch($arr, $target) {
$left = 0;
$right = count($arr) - 1;
while ($left <= $right) {
$mid = intval(($left + $right) / 2);
if ($arr[$mid] == $target) {
return $mid; // Return the index of the target value
}
if ($arr[$mid] < $target) {
$left = $mid + 1; // Continue searching in the right half
} else {
$right = $mid - 1; // Continue searching in the left half
}
}
return -1; // Target value does not exist
}
<p>$arr = [1, 3, 5, 7, 9, 11, 15];<br>
$target = 7;<br>
$index = binarySearch($arr, $target);<br>
if ($index != -1) {<br>
echo "Target value $target found at index $index in the array";<br>
} else {<br>
echo "Target value $target does not exist in the array";<br>
}<br>
The code above defines the function binarySearch, which accepts an ordered array and a target value as input and returns the index of the target in the array or -1 if it does not exist.
The time complexity of binary search is O(logN), where N is the length of the array. Because the search range halves with each iteration, the performance is significantly better than linear search, making it ideal for quickly locating elements in large ordered arrays.
Binary search greatly reduces search time, especially with large datasets, by quickly pinpointing the target element and avoiding inefficient full-array traversal.
In scenarios with frequent search operations, applying binary search can lower overall time costs, reduce resource consumption, and enhance response speed and user experience.
This article introduced the principles, implementation, and performance analysis of PHP binary search. Mastering binary search is crucial for developing efficient PHP applications, enabling faster searches and optimized program performance. Developers are encouraged to understand and apply this algorithm effectively.