Skip to main content

GATE CSE 2017Algorithms › Program & Function TracingVerified

GATE CSE 2017 PYQ: Let A A A be an array of 31 31 31 numbers consisting of a sequence of 0 0 0 's followed by a sequence of 1 1…

Let AA 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 ii such that A[i]A\left [i \right ] is 1 by probing the minimum number of locations in AA. The worst case number of probes performed by an optimal algorithm is ____________.

    Answer

    5

    Approach

    Since the array is sorted as a block of 0s followed by a block of 1s, the transition point can be located by binary search. At each probe, compare A[mid] with 1: if A[mid]=1, the first 1 is at or to the left of mid; if A[mid]=0, it is to the right of mid. This halves the search interval each time.

    Binary search is optimal for this structured sorted array, and the worst-case probe count is ceil(log2 31) = 5.

    Reviewed by GateIQ Editorial Team: IIT & IISc Alumni.