Referring back to the searching problem (see Exercise 2.1-3), observe that if the sequence \(A\) is sorted, we can check the midpoint of the sequence against \(v\) and eliminate half of the sequence from further consideration. The

algorithm repeats this procedure, halving the size of the remaining portion of the sequence each time. Write pseudocode, either iterative or recursive, for binary search. Argue that the worst-case running time of binary search is \(\Theta(\lg n)\).binary search

Here is the pseudocode if you prefer iterative solutions …

And here is the recursive one …

Intuitively, in worst case, i.e. when \(v\) is not at all present in \(A\), we need to search over the whole array to return \(\text {NIL}\). In other words, we need to repeatedly divide the array by 2 and check either half for \(v\). So the running time is nothing but how many times the input size can be divided by 2, i.e. \(\lg n\).

For recursive case, we can write the recurrence as follows …

\[T(n) = \begin {cases} \Theta(1) & \text { if } n = 1, \\ T((n - 1)/2) + \Theta(1) & \text { if } n > 1 \end {cases}\]