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
  1. A. 2
  2. B. 1
  3. C. 4
  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.

More Pseudocode and Code Tracing questions

Exams that ask this topic