ProgrammingHardAccenture · Cognizant

Array a = [2, 5, 3, 5]. For every pair of positions i < j, count the pairs where a[i] is at most a[j] (a[i] <= a[j]). What is the printed count?

Array a = [2, 5, 3, 5]. For every pair of positions i < j, count the pairs where a[i] is at most a[j] (a[i] <= a[j]). What is the printed count?
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. 4
  2. B. 2
  3. C. 6
  4. D. 5

Correct answer: D. 5

The pairs with a[i] <= a[j] are (2,5), (2,3), (2,5), (5,5) and (3,5), which is 5. Forgetting the equal pair gives 4, reversing the comparison gives 2, and counting every pair gives 6.

More Pseudocode and Code Tracing questions

Exams that ask this topic