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- A. b d a c
- B. d b a c
- C. d b c a
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode? (Arrays are indexed from 0) Integer a[7] = {4, 2, 2, 8, 3, 3, 1}, cnt[0..8] = all 0…
- What will be the output of the following pseudocode? (Arrays are indexed from 0) Integer a[8] = {170, 45, 75, 90, 802, 24, 2, 66} List…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Integer lo = 1, hi = 1000…
- What will be the output of the following pseudocode? (^ is bitwise XOR) Integer x = 0 for (each i from 1 to 10) x = x ^ i end for Integer…
- What will be the output of the following pseudocode? (^ is XOR, & is AND, >> is right shift) Integer x = 21, z = 22 Integer y = x ^ (x >>…
- What will be the output of the following pseudocode? (code(c) is the ASCII code: 'A' = 65, 'a' = 97) Function cmp(String a, String b)…