ProgrammingVery hardTCS NQT · Accenture

The procedure below counts the inversions of the array [2, 4, 1, 3] (pairs i < j with a[i] > a[j]) by checking all pairs. What is printed?

The procedure below counts the inversions of the array [2, 4, 1, 3] (pairs i < j with a[i] > a[j]) by checking all pairs. What is printed?
count = 0
for i = 0 to n - 2
    for j = i + 1 to n - 1
        if a[i] > a[j] then count = count + 1
    end for
end for
Print count
  1. A. 1
  2. B. 6
  3. C. 2
  4. D. 3

Correct answer: D. 3

The inversions are (2,1), (4,1) and (4,3), so the count is 3. Checking only adjacent pairs finds 1, counting all pairs gives 6, and comparing elements two apart gives 2.

More Pseudocode and Code Tracing questions

Exams that ask this topic