ProgrammingModerateTCS NQT · Accenture

The array a = [3, 1, 2, 4] is sorted in ascending order by selection sort, and the procedure below counts the total number of element comparisons made (each inner test of a[j] < a[min] counts as one comparison). What is printed?

The array a = [3, 1, 2, 4] is sorted in ascending order by selection sort, and the procedure below counts the total number of element comparisons made (each inner test of a[j] < a[min] counts as one comparison). What is printed?
cmp = 0
for i = 0 to n - 2
    m = i
    for j = i + 1 to n - 1
        cmp = cmp + 1
        if a[j] < a[m] then m = j
    end for
    swap a[i], a[m]
end for
Print cmp
  1. A. 2
  2. B. 7
  3. C. 9
  4. D. 6

Correct answer: D. 6

The inner loop runs 3 + 2 + 1 = 6 comparisons for n = 4, regardless of the data. Counting the swaps gives 2, the closed form with an extra 1 gives 7, and starting the inner loop at i adds self-comparisons to give 9.

More Pseudocode and Code Tracing questions

Exams that ask this topic