ProgrammingVery hardTCS NQT · Accenture

Array a = [3, 1, 2, 5, 4] is sorted by bubble sort: in each pass adjacent pairs out of order are swapped (a[j] > a[j+1]). What is the total number of swaps printed?

Array a = [3, 1, 2, 5, 4] is sorted by bubble sort: in each pass adjacent pairs out of order are swapped (a[j] > a[j+1]). What is the total number of swaps printed?
swaps = 0
repeat for each pass over j = 0 to n - 2
    if a[j] > a[j+1] then swap a[j] and a[j+1]; swaps = swaps + 1
Print swaps
  1. A. 20
  2. B. 3
  3. C. 7
  4. D. 10

Correct answer: B. 3

Each swap removes exactly one inversion, and the inversions here are (3,1), (3,2) and (5,4), so three swaps happen. Counting comparisons gives 20, counting non-inversions gives 7, and counting the out-of-order adjacent pairs in each pass without swapping gives 10.

More Pseudocode and Code Tracing questions

Exams that ask this topic