ProgrammingModerateSSC CGL Tier 2 · IBPS PO Mains

Array a = [3, 1, 2]. The procedure below performs a stable count of the number of ways the array can be read in increasing order using only adjacent swaps, which equals the number of inversions. What is printed?

Array a = [3, 1, 2]. The procedure below performs a stable count of the number of ways the array can be read in increasing order using only adjacent swaps, which equals the number of inversions. What is printed?
inv = 0
for i = 0 to n - 1
    for j = i + 1 to n - 1
        if a[i] > a[j] then inv = inv + 1
    end for
end for
Print inv
  1. A. 1
  2. B. 3
  3. C. 6
  4. D. 2

Correct answer: D. 2

The inversions are (3,1) and (3,2), so the count is 2. Counting non-inversions gives 1, counting positions out of sorted place gives 3, and the ordered count n(n-1) gives 6.

More Pseudocode and Code Tracing questions

Exams that ask this topic