ProgrammingVery hardAmazon OA · Infosys SP

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer a[6] = {3, 1, 2, 6, 4, 5}, swaps = 0, m, n = 6
for (each i from 0 to n - 2)
    m = i
    for (each j from i + 1 to n - 1)
        if (a[j] < a[m])
            m = j
        end if
    end for
    if (m != i)
        swap(a[i], a[m])
        swaps = swaps + 1
    end if
end for
Print swaps
  1. A. 5
  2. B. 6
  3. C. 3
  4. D. 4

Correct answer: D. 4

Selection sort swaps only when the minimum is out of place. The array {3, 1, 2, 6, 4, 5} has two cycles of length 3 ({3,1,2} and {6,4,5}), each fixed with 2 swaps, so swaps = 4. 6 is the inversion count, and 5 = n − 1.

More Pseudocode and Code Tracing questions

Exams that ask this topic