ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Record r[4] = {(3, 'a'), (1, 'b'), (3, 'c'), (1, 'd')}     // (key, letter)
for (each i from 0 to 2)
    Integer m = i
    for (each j from i + 1 to 3)
        if (r[j].key < r[m].key)
            m = j
        end if
    end for
    swap(r[i], r[m])
end for
Print r[0].letter, r[1].letter, r[2].letter, r[3].letter
  1. A. b d a c
  2. B. d b a c
  3. C. d b c a
  4. D. b d c a

Correct answer: D. b d c a

Selection sort swaps over long distances. i = 0: the first key 1 is b, swapped with a → b, a, c, d. i = 1: the smallest key among a, c, d is d (key 1), swapped with a → b, d, c, a. i = 2: c and a have equal keys, no change. Output b d c a: a and c have switched order, so the sort is not stable.

More Pseudocode and Code Tracing questions

Exams that ask this topic