ProgrammingVery hardGoldman Sachs OA · Capgemini

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer a[5] = {2, 3, 4, 5, 1}, passes = 0, n = 5
Boolean swapped
for (each i from 0 to n - 2)
    swapped = false
    passes = passes + 1
    for (each j from 0 to n - 2 - i)
        if (a[j] > a[j + 1])
            swap(a[j], a[j + 1])
            swapped = true
        end if
    end for
    if (not swapped)
        break
    end if
end for
Print passes
  1. A. 1
  2. B. 2
  3. C. 5
  4. D. 4

Correct answer: D. 4

A small number at the end moves left only one place per pass of bubble sort, so the 1 needs 4 passes to reach the front, and every one of them swaps. The early exit never triggers, and the loop ends after its 4 allowed passes.

More Pseudocode and Code Tracing questions

Exams that ask this topic