Searching

AP Computer Science A· difficulty 3/5

int[] a = {1, 3, 5, 7, 9, 11, 13};
int target = 7;
int lo = 0, hi = a.length - 1;
int result = -1;
while (lo <= hi) {
  int mid = (lo + hi) / 2;
  if (a[mid] == target) { result = mid; break; }
  else if (a[mid] < target) lo = mid + 1;
  else hi = mid - 1;
}

What is result?

  • A

    -1

  • B

    2

  • C

    4

  • D

    3

    check_circle

Explanation

Binary search: mid=3 (a[3]=7) matches target, so result=3.

Want 10 more like this — adaptive to your weak spots?

Related questions