Open In App

Algorithms | Searching | Question 2

Like Article
Like
Save
Share
Report

Which of the following is correct recurrence for worst case of Binary Search?

(A)

T(n) = 2T(n/2) + O(1) and T(1) = T(0) = O(1)

(B)

T(n) = T(n-1) + O(1) and T(1) = T(0) = O(1)

(C)

T(n) = T(n/2) + O(1) and T(1) = T(0) = O(1)

(D)

T(n) = T(n-2) + O(1) and T(1) = T(0) = O(1)



Answer: (C)

Explanation:

Following is a typical implementation of Binary Search. 

// Searches x in arr[low..high].  If x is present, then returns its index, else -1
int binarySearch(int arr[], int low, int high, int x)
{
    if(high >= low)
    {
        int mid = low + (high - low)/2;
        if (x == arr[mid])
            return mid;
        if (x> arr[mid])
            return binarySearch(arr, (mid + 1), high);
        else
            return binarySearch(arr, low, (mid -1));
    }

    return -1;
}

In Binary Search, we first compare the given element x with middle of the array. If x matches with middle element, then we return middle index. Otherwise, we either recur for left half of array or right half of array. So recurrence is T(n) = T(n/2) + O(1)

Hence Option(C) is the correct answer


Quiz of this Question
Please comment below if you find anything wrong in the above post


Last Updated : 28 Jun, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads