1 view
Implement binary search on a sorted array.
Asked at
AI answer
For an array sorted in ascending order, binary search takes O(log n) time and O(1) additional space. The function returns the index of the found element or -1; if there are duplicates, it may return any matching index.
function binarySearch(array $items, int $target): int
{
$left = 0;
$right = count($items) - 1;
while ($left <= $right) {
$mid = $left + intdiv($right - $left, 2);
if ($items[$mid] === $target) {
return $mid;
}
if ($items[$mid] < $target) {
$left = $mid + 1;
} else {
$right = $mid - 1;
}
}
return -1;
}
This assumes the array has contiguous indexes, is sorted in ascending order, and that the values and target are integers.
Also asked at Astrum Entertainment
- What is the difference between the equality operator '==' and the strict equality operator '===' in PHP?
- How can you perform binary search on a sorted array of infinite or unknown length (when the count function is unavailable)?
- Why is rounding (floor) used when calculating the midpoint, what other ways are there to remove the fractional part in PHP, and which is more optimized (the difference between a function and a language construct)?
- Implement a weighted Round Robin algorithm (distributing requests across arrays according to their weights, for example 30%, 50%, 20%).
- What should a binary search function return if the target element is not found: -1 or an exception? Which is more appropriate?
Similar questions
- What is the time and space complexity of your implementation?
- What is a B-tree?
- What if we needed to reverse a string containing Cyrillic characters? Would this implementation work, and what would need to change?
- How to implement index-based access in a singly linked list and in an array?
- What will be the output when array_search() is used in an if condition?