Popular Posts

Wednesday, August 3, 2011

CLRS Exercises 2.3-5 Binary search

Problem:

Binary search is an algorithm that 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 Θ(lg n).

Solution:

  1. If there are 2^i elements then the height of the tree will be i+1
  2. At each level we will just do comparison [key with middle element] which is a constant time O(1)
  3. So for any n, height of the tree will be log n + 1
  4. Thus, worst case running complexity will be Θ(lg n).

Complexity: Θ(lg n).
Code:


No comments:

Post a Comment