Floor in a Sorted Array
beginnerFinds the largest element ≤ target in a sorted array using binary search with a "last valid" tracker.
PhaseInit
x5
Mid—
UB—
upper_bound(arr, x) = first i where arr[i] > xfloor = arr[upper_bound − 1]
lo
mid
hi
1
[0]2
[1]8
[2]10
[3]11
[4]12
[5]19
[6]mid / UB
≤ x / floor
> x (too big)
search window
upper_bound approach: lo=0, hi=7 (half-open [lo, hi)). Find first index where arr[i] > x=5.
1 / 10