Let A be an array of 31 numbers consisting of a sequence of 0’s ...
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.
View all questions of this test
Let A be an array of 31 numbers consisting of a sequence of 0’s ...
Problem Analysis:
- We are given an array A of length 31, consisting of a sequence of 0s followed by a sequence of 1s.
- We need to find the smallest index i such that A[i] is 1.
- We want to determine the worst-case number of probes performed by an optimal algorithm.
Key Insight:
- Since the array A is sorted in a specific way (sequence of 0s followed by a sequence of 1s), we can take advantage of this property to devise an efficient algorithm.
Algorithm:
1. Initialize two pointers, left and right, pointing to the first and last elements of the array A respectively.
2. While left <=>=>
- Calculate the middle index mid as (left + right) / 2.
- If A[mid] is 0, then the 1s sequence is on the right side of mid. So, set left = mid + 1.
- If A[mid] is 1, then the 1s sequence starts at or before mid. So, set right = mid.
3. Return the value of left as the smallest index i such that A[i] is 1.
Explanation:
- In each iteration of the algorithm, we are effectively dividing the search space in half.
- Initially, the search space is the entire array A.
- At each step, we are eliminating half of the remaining elements.
- The algorithm terminates when there is only one element left in the search space, which is the desired index i.
- Therefore, the number of probes performed by the algorithm is equal to the number of iterations taken to reach the termination condition.
- In this case, the search space is divided into two halves in each iteration, resulting in a worst-case time complexity of O(log n), where n is the length of the array A.
- In the given problem, n = 31, so the worst-case number of probes performed by the optimal algorithm is log₂(31) ≈ 5.
Conclusion:
- The worst-case number of probes performed by an optimal algorithm to find the smallest index i such that A[i] is 1 is 5.