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- A. 6
- B. 9
- C. 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Prefix sums are computed for a = [4, 1, 7, 3, 2, 8] with P[0] = 0 and P[k] = a[1] + ... + a[k]. A range sum for 1-based positions l to r…
- Array a = [4, 1, 7, 3, 2, 8] (three queries are not needed here). The procedure below counts the elements that are strictly greater than…
- Array a = [1, 2, 3, 4, 5, 6, 7] is rotated to the right by k = 3 positions: each element moves k places to the right with wrap-around. The…
- Lomuto partition is applied to a = [3, 8, 2, 5, 1, 4] with the pivot equal to the last element. For j = 0 to n - 2: if a[j] <= pivot, then…
- For the array a = [2, 9, 4, 7, 5, 6, 3] (indices 0 to 6), the procedure below computes the sum of the maximum values of all contiguous…
- Array a = [3, 1, 4, 1, 5, 9, 2, 6] is scanned from left to right. The procedure below counts the positions i (from 2 to n) where a[i] is…