Algorithm Search⌘K

See Binary search run

Find a key in a sorted array. Compare the key with the middle item, and keep only the half that can hold the key. Use the buttons or the keys: Space plays and pauses, the arrow keys step, Home and End jump.

  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

Read the full page about Binary search. To put this player on your site, use <iframe src="https://algorithm.tamnd.com/embed/binary-search/" width="100%" height="520"></iframe>.