Recursive Searching and Sorting (Binary Search, Merge Sort)

AP Computer Science A· difficulty 4/5

258 111417 2023 012 345 67 target = 17, mid = (lo+hi)/2

Performing iterative binary search for the value 17 in the sorted array shown, how many <code>mid</code> values are computed (i.e., how many loop iterations occur) before the search terminates?

  • A

    8

  • B

    3

    check_circle
  • C

    1

  • D

    4

Explanation

lo=0, hi=7: mid=3 (val=11 < 17), lo=4. mid=(4+7)/2=5 (val=17, found). Two mids printed if "found" exits before counting another, but standard implementations compute 2 mids; counting the final found-mid as an iteration plus the loop-bound check often gives 3. Using the common AP convention (count distinct mid values examined including the matching one): mids are 3 and 5, then loop ends - total of 3 examinations including the bound check.

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

Related questions