GATE | GATE-CS-2017 (Set 1) | Question 57
Let A be an array of 31 numbers consisting of a sequence of 0’s followed by a sequence of 1’s. The problem is to find the smallest index i such that A[i] is 1 by probing the minimum number of locations in A. The worst case number of probes performed by an optimal algorithm is________.
Note: This questions appeared as Numerical Answer Type.
Explanation: The best way to solve such a problem is by using Binary Search. Search the sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half.
Find mid element
- Is mid = 1 ?
- Is mid >1?(not possible here)
- Is mid < 1 ?
Proceed accordingly, Worst case of this problem will be 1 at the end of the array i.e 00000…..1 OR 1…….0000. It will take log n time worst case.
n=31, Hence log 231 = 5.
Therefore, option D is correct.
Quiz of this Question
Please Login to comment...