Number of guesses binary search would take to reach number

154 Views Asked by At

Essentially, given a start of an inclusive integer range $s$, an end of the range $f$ such that $s \le f$, and an integer $n$ such that $s \le n \le f$, how many guesses would binary search take to find $n$?

For example, let $s = 1$, $f = 20$, and $n = 9$. Then, binary search would take $5$ guesses as follows: 10, 5, 7, 8, 9.

For another example, let $s = 1$, $f = 20$, and $n = 10$. Then, binary search would take $1$ guess as follows: $10$.

Can this be generalized to a formula with these 3 inputs?

Here is some pseudocode for reference that calculates the number of guesses for a specific combination with $g$ being the current number of guesses and $m$ being the current guess:

binary_search(s, f, n)
    g = 0
    
    while s <= f
        g = g + 1
        m = int((s + f) / 2)
        
        if m == n
            return g
        else if m < n
            s = m + 1
        else
            f = m - 1

Edit:

Using the information provided by ronno, here is the recurrence that we would have to solve to find the closed-form expression after performing the transformations $(s, f, n) \mapsto (0, f - s, n - s)$:

Note: Removed $s$ below as $s = 0$ after the above transformations. $$ \text{binary_search}(f, n) = \begin{cases} 1 &\text{if } m = n \\ 1 + \text{binary_search}(f - m - 1, n - m - 1) &\text{if } m < n \\ 1 + \text{binary_search}(m - 1, n) &\text{otherwise} \end{cases} \\ \text{where } m = \left \lfloor \frac{f}{2} \right \rfloor $$