Binary search finds a target in a sorted array by repeatedly halving the search range. Each comparison eliminates half of the remaining elements, giving O(log n) time.
The idea
Look at the middle element. If it equals the target, done. If the target is smaller, search the left half; if larger, search the right half. Repeat until found or the range is empty.
Example
():
lo, hi = , (arr) -
lo <= hi:
mid = (lo + hi) //
arr[mid] == target:
mid
arr[mid] < target:
lo = mid +
:
hi = mid -
-
binary_search([, , , , ], )
