ProgrammingHardAccenture · Cognizant pattern

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

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

Correct answer: C. [1, 1, 2, 3, 4, 5, 6, 9]

This is selection sort: on each outer pass, it finds the minimum of the unsorted remainder and swaps it into place, eventually producing the fully sorted array [1, 1, 2, 3, 4, 5, 6, 9].

More Pseudocode and Code Tracing questions

Exams that ask this topic