ProgrammingHardTCS NQT · Accenture
Array [4, 1, 3, 2] is sorted by selection sort: for each position i, find the minimum of the unsorted part and swap it into position i, but only when its index differs from i. What is the number of swaps printed?
Array [4, 1, 3, 2] is sorted by selection sort: for each position i, find the minimum of the unsorted part and swap it into position i, but only when its index differs from i. What is the number of swaps printed?
swaps = 0
for i = 0 to n - 2
m = index of minimum in a[i..n-1]
if m != i then swap a[i], a[m]; swaps = swaps + 1
end for
Print swaps- A. 2
- B. 6
- C. 4
- D. 3
Correct answer: A. 2
Position 0 swaps 4 with 1, position 1 swaps 4 with 2, and position 2 already holds 3, so there are two swaps. Counting all pairs gives six, counting inversions gives four, and swapping even when the minimum is already in place gives 3.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Sorted array a = [1, 2, 3, 5, 8, 9] and limit L = 10. Count the pairs of distinct positions i < j with a[i] + a[j] <= L using two…
- The string s = "aaabbbcc" is cut down so that no two adjacent letters are equal, by deleting characters. The greedy keeps a character when…
- A binary string s = "1100101" is to be made alternating. Two targets are possible: "0101010..." and "1010101...", each the same length as…
- Count how many copies of the word BALLOON can be formed from the letters of "lloolldnaubbalo" (each letter used at most once per copy)…
- Children have ratings r = [1, 0, 2, 2, 1]. Each child gets at least one candy, and a child with a higher rating than a neighbour gets more…
- Let x = 0. For i from 1 to 10: if i mod 3 == 0 then x = x + i, otherwise x = x - 1. What is printed? x = 0 for i = 1 to 10 if i mod 3 == 0…