Binary search · Compiler

Binary search

Count the middle values inspected by binary search. Start with inclusive zero-based indices lo = 0 and hi = n - 1. While lo <= hi, inspect the value at floor((lo + hi) / 2). Stop on equality. Otherwise discard the middle and the half that cannot contain the target. Count the matching inspection if there is one.

Input
Line 1 contains n (0 to 100) and the integer target. The remaining n integers form an array sorted in nondecreasing order. The target and all values are from -1000 to 1000.
Output
Print the total number of inspections, including all inspections made during an unsuccessful search.

Compiler Explorer runs your code when you run or check it.

Loading your exercise draft…