Searching
Binary Search First Occurrence
Find the first copy of a duplicated target by recording matches and continuing to search the left half.
Algorithm
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.
Basic Implementation
basic.php
Replay: real traced execution (multi-file project)
<?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";
arr ← [1, 2, 4, 4, 4, 7, 9], target ← 4, result ← -1
1<?php2$arr = [1, 2, 4, 4, 4, 7, 9];values this step[1, 2, 4, 4, 4, 7, 9]arr4target-1resulthi ← 2, mid ← 3, result ← 3
7while ($lo <= $hi) {8 $mid = intdiv($lo + $hi, 2);9 if ($arr[$mid] == $target) {values this step6 → 2hi3mid3result0lolo ← 2, mid ← 1
7while ($lo <= $hi) {8 $mid = intdiv($lo + $hi, 2);9 if ($arr[$mid] == $target) {values this step0 → 2lo1mid2hi3resulthi ← 1, result ← 2, mid ← 2
7while ($lo <= $hi) {8 $mid = intdiv($lo + $hi, 2);9 if ($arr[$mid] == $target) {values this step2 → 1hi3 → 2result2mid2lostdout ← 2
17}18echo $result . "\n";values this step2stdout2result
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.