ProgrammingHardTCS NQT · Accenture
Recursive merge sort splits an array of length n into halves of length n div 2 and n minus n div 2, and calls itself on each half unless the length is 1 or less. The procedure below counts the calls for an array of length 8 (including the root call). What is printed?
Recursive merge sort splits an array of length n into halves of length n div 2 and n minus n div 2, and calls itself on each half unless the length is 1 or less. The procedure below counts the calls for an array of length 8 (including the root call). What is printed?
function sort(length)
count the call
if length <= 1 then return
sort(length div 2); sort(length - length div 2)
end function
Print the number of calls for length 8- A. 4
- B. 7
- C. 13
- D. 15
Correct answer: D. 15
Halving 8 gives 4, 2 and 1, and each level doubles the number of calls: 1 + 2 + 4 + 8 = 15 calls in total. Making only one child call gives 4, stopping at length 2 gives 7, and using length 7 by mistake gives 13.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- The loop below multiplies i by 3 each time while i is less than 1000, starting from i = 1, and counts the iterations. What is printed? i =…
- A nested loop counts the pairs (i, j) with 1 <= j <= i <= 6 that also satisfy i + j even. The procedure prints the count. What is printed?…
- The procedure below counts the numbers i from 1 to 100 whose binary form has exactly three 1 bits (bits are counted by repeatedly taking n…
- A string of parentheses "(()())((" is scanned by the procedure below. The variable open counts unmatched '(' at the end, and the procedure…
- The procedure below scans the string "abracadabra" from left to right and counts how many letters are repeats of an earlier letter (a…
- A string is a rotation of another when it can be obtained by moving some prefix to the end. The procedure below checks whether…