ProgrammingHardAccenture · Cognizant pattern

How many swaps does this pseudocode perform? (Arrays are indexed from 0.)

How many swaps does this pseudocode perform? (Arrays are indexed from 0.)
Integer arr[5] = {5, 1, 4, 2, 8}
Integer swaps = 0
for (each i from 0 to 3)
    for (each j from 0 to 3 - i)
        if (arr[j] > arr[j + 1])
            swap(arr[j], arr[j + 1])
            swaps = swaps + 1
        end if
    end for
end for
Print swaps
  1. A. 10
  2. B. 5
  3. C. 4
  4. D. 3

Correct answer: C. 4

Each bubble-sort swap fixes exactly one inversion, so the number of swaps equals the number of inversions: (5,1), (5,4), (5,2), (4,2) = 4. The 10 comparisons are the trap.

More Pseudocode and Code Tracing questions

Exams that ask this topic