ProgrammingVery hardTCS NQT · Accenture
Sorted array a = [1, 3, 6, 6, 6, 9]. The lower-bound binary search below finds the first index whose value is at least x = 6. What is printed?
Sorted array a = [1, 3, 6, 6, 6, 9]. The lower-bound binary search below finds the first index whose value is at least x = 6. What is printed?
lo = 0; hi = n
while lo < hi
mid = (lo + hi) div 2
if a[mid] < x then lo = mid + 1 else hi = mid
end while
Print lo- A. 5
- B. 3
- C. 1
- D. 2
Correct answer: D. 2
The first 6 is at index 2, which is the lower bound. Using <= moves past all the 6s and gives the upper bound 5, counting the 6s gives 3, and a broken hi update returns 1.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Array a = [2, 4, 6, 8, 10]. The loop below sums i a[i] over the 0-based indices i. What is printed? total = 0 for i = 0 to 4 total = total…
- The array [0, 1, 0, 3, 12] has its zeros moved to the end while keeping the order of the other values, by a two-pointer pass that writes…
- For the array a = [7, 2, 4, 9, 1, 5] the procedure below computes the sum of the minimum of every contiguous window of length 2 (windows…
- The array a = [3, 1, 2, 4] is sorted in ascending order by selection sort, and the procedure below counts the total number of element…
- Array a = [1, 2, 3, 5, 4] is checked by the procedure below, which performs bubble sort with an early-exit flag (a pass with no swaps ends…
- Array a = [3, 8, 5, 6, 7] has its odd values summed by the procedure below, and the result is printed. What is printed? total = 0 for each…