AlgoFrames

Mid values

Warm-up · Trace the algorithm · about 4 min

Binary search looks for 38 in the sorted array [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]. Before each look, work out the index of mid.

Use mid = (lo + hi) / 2, rounded down.

Example 1

Input:

{"values":[2,5,8,12,16,23,38,56,72,91],"target":38}

Output:

6

38 sits at index 6.

Constraints

  • The trace uses the input shown.
  • Answer with an index, not a value.

Learn the idea first: Binary search, a visual lesson.

More Binary search problems