ProgrammingModerateTCS NQT · Accenture
The array a = [3, 1, 2, 4] is sorted in ascending order by selection sort, and the procedure below counts the total number of element comparisons made (each inner test of a[j] < a[min] counts as one comparison). What is printed?
The array a = [3, 1, 2, 4] is sorted in ascending order by selection sort, and the procedure below counts the total number of element comparisons made (each inner test of a[j] < a[min] counts as one comparison). What is printed?
cmp = 0
for i = 0 to n - 2
m = i
for j = i + 1 to n - 1
cmp = cmp + 1
if a[j] < a[m] then m = j
end for
swap a[i], a[m]
end for
Print cmp- A. 2
- B. 7
- C. 9
- D. 6
Correct answer: D. 6
The inner loop runs 3 + 2 + 1 = 6 comparisons for n = 4, regardless of the data. Counting the swaps gives 2, the closed form with an extra 1 gives 7, and starting the inner loop at i adds self-comparisons to give 9.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Array a = [1, 2, 3, 5, 4] is checked by the procedure below, which performs bubble sort with an early-exit flag (a pass with no swaps ends…
- Array a = [3, 8, 5, 6, 7] has its odd values summed by the procedure below, and the result is printed. What is printed? total = 0 for each…
- Array a = [0, 2, 2, 3, 5]. The procedure below counts the positions i (0-based) where a[i] equals i. What is printed? count = 0 for i = 0…
- For the array a = [1, 2, 3, 4, 5, 6], the procedure below counts the contiguous subarrays of length 3 whose sum is divisible by 3. What is…
- Two numbers are formed from the arrays a = [1, 3, 5] and b = [2, 3, 6] by merging them into one sorted list. The procedure below prints…
- For the array a = [-1, 4, -2, 6, -3, 5], the procedure below finds the maximum sum of a contiguous window of exactly 3 elements (windows…