ProgrammingHardTCS NQT · Accenture pattern

What will be the output of the following pseudocode (counting inversions, brute force)? (Arrays are indexed from 0.)

What will be the output of the following pseudocode (counting inversions, brute force)? (Arrays are indexed from 0.)
Integer arr[5] = {2, 4, 1, 3, 5}
Integer cnt = 0
for (each i from 0 to 4)
    for (each j from i + 1 to 4)
        if (arr[i] > arr[j])
            cnt = cnt + 1
        end if
    end for
end for
Print cnt
  1. A. 2
  2. B. 4
  3. C. 3
  4. D. 5

Correct answer: C. 3

The out-of-order pairs (i<j but arr[i]>arr[j]) are (2,1), (4,1), (4,3) -- three inversions in total.

More Pseudocode and Code Tracing questions

Exams that ask this topic