ProgrammingVery hardTCS NQT · Accenture
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 the sort). It prints the number of passes performed, including the final pass that makes no swaps. What is printed?
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 the sort). It prints the number of passes performed, including the final pass that makes no swaps. What is printed?
passes = 0
repeat
swapped = false; passes = passes + 1
for j = 0 to n - 2
if a[j] > a[j+1] then swap; swapped = true
end for
until not swapped
Print passes- A. 2
- B. 1
- C. 4
- D. 8
Correct answer: A. 2
Only one swap is needed (5 and 4), which happens in pass 1, and pass 2 makes no swaps and stops the sort, so 2 passes run. Stopping on the first swapping pass gives 1, using n-1 gives 4, and counting comparisons over all passes gives 8.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- 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…
- Array a = [4, 9, 2, 8, 2, 7]. The procedure below counts the prefix records, that is, the positions i where a[i] is strictly greater than…