1. BINARY-SEARCH(A, x)
  2. 1lo ← 0, hi ← n ▷ the range is A[lo .. hi − 1]
  3. 2while lo < hi do
  4. 3mid ← lo + ⌊(hi − lo) / 2⌋ ▷ no overflow, unlike ⌊(lo + hi) / 2⌋
  5. 4if A[mid] < x then
  6. 5lo ← mid + 1 ▷ x is not in A[lo .. mid]
  7. 6else if A[mid] > x then
  8. 7hi ← mid ▷ x is not in A[mid .. hi − 1]
  9. 8else return mid
  10. 9return NIL
0 / 0
Use your own input

Type the input as JSON, in the same form as a preset.

Open the full player

Binary search on Algorithm