ProgrammingHardTCS NQT · Accenture

Array [4, 1, 3, 2] is sorted by selection sort: for each position i, find the minimum of the unsorted part and swap it into position i, but only when its index differs from i. What is the number of swaps printed?

Array [4, 1, 3, 2] is sorted by selection sort: for each position i, find the minimum of the unsorted part and swap it into position i, but only when its index differs from i. What is the number of swaps printed?
swaps = 0
for i = 0 to n - 2
    m = index of minimum in a[i..n-1]
    if m != i then swap a[i], a[m]; swaps = swaps + 1
end for
Print swaps
  1. A. 2
  2. B. 6
  3. C. 4
  4. D. 3

Correct answer: A. 2

Position 0 swaps 4 with 1, position 1 swaps 4 with 2, and position 2 already holds 3, so there are two swaps. Counting all pairs gives six, counting inversions gives four, and swapping even when the minimum is already in place gives 3.

More Pseudocode and Code Tracing questions

Exams that ask this topic