ProgrammingVery hardTCS NQT · Infosys · Capgemini

What will be the output of the following pseudocode? (Arrays are 0-indexed.)

What will be the output of the following pseudocode? (Arrays are 0-indexed.)
Integer a[7] = {5, 1, 4, 2, 8, 0, 3}
Integer swaps = 0, passes = 0
Boolean swapped
Repeat
    swapped = false
    For i = 0 to 5 - passes
        If a[i] > a[i + 1] Then
            Swap a[i], a[i + 1]
            swaps = swaps + 1
            swapped = true
        End If
    End For
    passes = passes + 1
Until swapped = false
Print passes, swaps
  1. A. 5 12
  2. B. 6 13
  3. C. 6 12
  4. D. 7 12

Correct answer: C. 6 12

Each adjacent swap removes exactly one inversion, and the array has 12 inversions, so swaps = 12. The array becomes sorted during pass 5, and pass 6 finds nothing to swap, which ends the loop: passes = 6.

More Pseudocode and Code Tracing questions

Exams that ask this topic