ProgrammingHardAccenture · Cognizant
Array a = [2, 5, 7, 10, 12] is searched for the number of elements less than or equal to 7 by a binary search that finds the boundary index (the first index whose value is greater than 7). What is the index printed?
Array a = [2, 5, 7, 10, 12] is searched for the number of elements less than or equal to 7 by a binary search that finds the boundary index (the first index whose value is greater than 7). What is the index printed?
lo = 0; hi = n
while lo < hi
mid = (lo + hi) div 2
if a[mid] <= 7 then lo = mid + 1 else hi = mid
end while
Print lo- A. 2
- B. 4
- C. 5
- D. 3
Correct answer: D. 3
Values up to 7 are 2, 5, 7 so the first index with a larger value is 3. Using a strict test returns 2, counting the values up to 7 and adding one gives 4, and the array length 5 is a different number.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- The procedure below counts the pairs (i, j) with i < j and a[i] + a[j] = 8, for the array a = [1, 5, 3, 3, 7, 4, 6, 2]. What is printed?…
- Array a = [4, 4, 6, 1, 1] has a value appearing more than once. The procedure below counts the values that appear exactly twice. What is…
- Array a = [5, -3, 5] is treated as circular. The maximum circular subarray sum (a contiguous block that may wrap around the end) is found…
- 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…
- 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…