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.swift
let arr = [1, 2, 4, 4, 4, 7, 9]
let target = 4
var lo = 0
var hi = arr.count - 1
var result = -1
while lo <= hi {
let mid = lo + (hi - lo) / 2
if arr[mid] == target {
result = mid
hi = mid - 1
} else if arr[mid] < target {
lo = mid + 1
} else {
hi = mid - 1
}
}
print(result)
Complexity
- Time: O(log n)
- Space: O(1)
Implementation notes
- This checked source uses top-level Swift statements, not a helper function:
let arr = [1, 2, 4, 4, 4, 7, 9]andlet target = 4are immutable[Int]/Intbindings. var lo,var hi, andvar resultare the mutable search state;resultstarts at-1as the not-found sentinel.- The loop guard is
while lo <= hi, andlet mid = lo + (hi - lo) / 2uses integer division onIntvalues to choose the current index. - On
arr[mid] == target, the code recordsresult = midand moveshi = mid - 1so duplicates to the left stay visible; smaller values movelo = mid + 1. - The trace records
mid = 3settingresultto3andhito2, thenmid = 1movingloto2, thenmid = 2updating the first occurrence toresult = 2. - When
lo > hi,print(result)writes the Swift integer output2.
execution replay
The checked-in replay follows the language-neutral state table for `search-binary-first`.
cross-language comparison
This Swift DSA version keeps the same data and final output as every other DSA book in this wave.