ProgrammingVery hardAmazon OA · Infosys SP
What will be the output of the following pseudocode?
What will be the output of the following pseudocode?
Integer a[6] = {3, 1, 2, 6, 4, 5}, swaps = 0, m, n = 6
for (each i from 0 to n - 2)
m = i
for (each j from i + 1 to n - 1)
if (a[j] < a[m])
m = j
end if
end for
if (m != i)
swap(a[i], a[m])
swaps = swaps + 1
end if
end for
Print swaps- A. 5
- B. 6
- C. 3
- D. 4
Correct answer: D. 4
Selection sort swaps only when the minimum is out of place. The array {3, 1, 2, 6, 4, 5} has two cycles of length 3 ({3,1,2} and {6,4,5}), each fixed with 2 swaps, so swaps = 4. 6 is the inversion count, and 5 = n − 1.
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? Integer a[6] = {5, 2, 4, 6, 1, 3}, shifts = 0, key, j for (each i from 1 to 5) key =…
- What will be the output of the following pseudocode? (code(c) gives a letter's character code and char(k) the reverse; 'A'..'Z' have…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Integer n = 987654321, c = 0…
- What will be the output of the following pseudocode? Integer a[6] = {1, 2, 4, 5, 7, 9} Integer i = 0, j = 5, c = 0 while (i < j) if (a[i]…
- What will be the output of the following pseudocode? Integer a[7] = {2, -1, 4, 3, -2, 5, 1} Integer s = a[0] + a[1] + a[2], best = s for…
- What will be the output of the following pseudocode? Integer a[3] = {-3, -1, -4} Integer cur = 0, best = 0 for (each i from 0 to 2) cur =…