ProgrammingHardInfosys · Capgemini pattern

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer a[] = {5, 1, 4, 2, 3}, c = 0
for (i = 0 to 4)
    for (j = i + 1 to 4)
        if (a[i] > a[j]) c = c + 1
    end for
end for
Print c
  1. A. 4
  2. B. 10
  3. C. 5
  4. D. 6

Correct answer: D. 6

c counts inversions: 5 is greater than the 4 values after it; 4 > 2 and 4 > 3; 1, 2, 3 add nothing → 6. This equals the number of swaps bubble sort would make. O(n²); merge sort counts them in O(n log n).

More Pseudocode and Code Tracing questions

Exams that ask this topic