ProgrammingVery hardTCS NQT · Accenture

Array a = [8, 4, 2, 1, 7, 5]. The number of inversions (pairs i < j with a[i] > a[j]) is the number of out-of-order pairs, and merge sort counts them while merging. What is the number of inversions printed?

Array a = [8, 4, 2, 1, 7, 5]. The number of inversions (pairs i < j with a[i] > a[j]) is the number of out-of-order pairs, and merge sort counts them while merging. What is the number of inversions 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. 6
  2. B. 9
  3. C. 4
  4. D. 5

Correct answer: B. 9

8 is ahead of 4, 2, 1, 7 and 5 (5 pairs), 4 is ahead of 2 and 1 (2 pairs), 2 is ahead of 1 (1 pair), and 7 is ahead of 5 (1 pair), for 9 in total. Counting the ascending pairs gives 6, counting only adjacent descents gives 4, and skipping adjacent pairs gives 5.

More Pseudocode and Code Tracing questions

Exams that ask this topic