Searching
Binary Search First Occurrence
Find the first copy of a duplicated target by recording matches and continuing to search the left half.
Algorithm
Basic Implementation
basic.php
<?php
$arr = [1, 2, 4, 4, 4, 7, 9];
$target = 4;
$lo = 0;
$hi = count($arr) - 1;
$result = -1;
while ($lo <= $hi) {
$mid = intdiv($lo + $hi, 2);
if ($arr[$mid] == $target) {
$result = $mid;
$hi = $mid - 1;
} elseif ($arr[$mid] < $target) {
$lo = $mid + 1;
} else {
$hi = $mid - 1;
}
}
echo $result . "\n";
Complexity
- Time: O(log n)
- Space: O(1)
Implementation notes
- The sorted PHP array literal is
[1, 2, 4, 4, 4, 7, 9], and$targetis4. $lostarts at0,$histarts atcount($arr) - 1, and$result = -1is the not-found sentinel until a match is recorded.- The loop guard is
while ($lo <= $hi), so each pass keeps the active search window explicit. $mid = intdiv($lo + $hi, 2)uses PHP integer division for the midpoint.- A match uses
$arr[$mid] == $target, records$result = $mid, then sets$hi = $mid - 1so the loop keeps looking for an earlier duplicate. - If
$arr[$mid] < $target,$lomoves right; otherwise$himoves left. - The trace starts with
lo=0,hi=6,mid=3; value4matches, soresult=3andhi=2. - Next
mid=1reads value2, solomoves to2whileresultstays3. - The final checked step has
lo=2,hi=2,mid=2; value4matches,resultbecomes2, andhi=1ends the loop. echo $result . "\n";prints2, the first index of4in the pinned data.
execution replay
The checked-in replay follows the language-neutral state table for `search-binary-first`.
cross-language comparison
This PHP DSA version keeps the same data and final output as every other DSA book in this wave.