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- A. 1
- B. 3
- C. 6
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Array a = [1, 3, 2, 3, 4, 1] is searched for the longest strictly increasing contiguous run. The procedure below returns its length. What…
- Array a = [5, 1, 4, 2, 3, 7]. The procedure below counts the interior local maxima, that is, positions i from 1 to n - 2 whose value is…
- The KMP prefix function pi[i] is the length of the longest proper prefix of s[0..i] that is also a suffix of it. For s = "abacabab" the…
- Pattern "aba" is searched in the text "abababa" with overlapping matches allowed. The procedure below counts the starting positions where…
- For the string s = "forgeeksskeegfor", the procedure below expands around each centre to find the length of the longest palindromic…
- Count the palindromic substrings (substrings of length 1 or more that read the same forwards and backwards, counted by position) of the…