ProgrammingHardAccenture · Cognizant
Binary search for the value 13 in the sorted array [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] uses lo = 0, hi = n - 1 and mid = (lo + hi) div 2. Each loop iteration is one probe (one mid examined). How many probes are made before the value is found?
Binary search for the value 13 in the sorted array [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] uses lo = 0, hi = n - 1 and mid = (lo + hi) div 2. Each loop iteration is one probe (one mid examined). How many probes are made before the value is found?
lo = 0; hi = n - 1; probes = 0
while lo <= hi
mid = (lo + hi) div 2; probes = probes + 1
if a[mid] == 13 then stop
else if a[mid] < 13 then lo = mid + 1 else hi = mid - 1
end while
Print probes- A. 4
- B. 7
- C. 3
- D. 5
Correct answer: A. 4
The probes examine mid = 4 (9), mid = 7 (15), mid = 5 (11), and mid = 6 (13), which is 4 probes. Counting the 1-based position gives 7, stopping one probe early gives 3, and adding one to the final count gives 5.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Array a = [8, 4, 2, 1, 7, 5]. The number of inversions (pairs i < j with a[i] > a[j]) is the number of out-of-order pairs, and merge sort…
- Prefix sums are computed for a = [4, 1, 7, 3, 2, 8] with P[0] = 0 and P[k] = a[1] + ... + a[k]. A range sum for 1-based positions l to r…
- Array a = [4, 1, 7, 3, 2, 8] (three queries are not needed here). The procedure below counts the elements that are strictly greater than…
- Array a = [1, 2, 3, 4, 5, 6, 7] is rotated to the right by k = 3 positions: each element moves k places to the right with wrap-around. The…
- Lomuto partition is applied to a = [3, 8, 2, 5, 1, 4] with the pivot equal to the last element. For j = 0 to n - 2: if a[j] <= pivot, then…
- For the array a = [2, 9, 4, 7, 5, 6, 3] (indices 0 to 6), the procedure below computes the sum of the maximum values of all contiguous…