CleverSphere

Binary search step by step

Binary search halves the range in every step, but it needs a sorted array.

Rules

  • mid = ⌊(left + right) / 2⌋
  • Smaller: right = mid − 1
  • Larger: left = mid + 1

Your turn

Three problems on this topic. Separate lists with commas.

  1. 1 · Binary search
  2. 2
  3. 3

Binary search for 44, mid = ⌊(left + right) / 2⌋, index from 0. Which indices are checked, in order?

[1, 7, 8, 12, 17, 33, 39, 44, 47, 57]

Indizes (comma-separated)

Found?

Worked example

Binary search for 24, mid = ⌊(left + right) / 2⌋, index from 0. Which indices are checked, in order?

[1, 6, 12, 13, 17, 24, 37, 39, 45, 50, 59]

Worked solution

  1. 1a[5] = 24

Typical mistake: After a comparison the middle is no longer in the range: mid + 1 or mid − 1.

Common questions

How many steps does it take?

At most about log₂(n) + 1.

Related

More topics