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
  1. A. 4
  2. B. 7
  3. C. 13
  4. 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.

More Pseudocode and Code Tracing questions

Exams that ask this topic