Data Structures & AlgorithmsHardTCS NQT · Product Company SDE

Problem: Bubble sort is run on [5, 2, 9, 1, 7, 3, 8, 6, 4] using the standard adjacent-swap pass (for i from 0 to n−2, swap a[j] and a[j+1] when a[j] > a[j+1]). How many swaps are performed in total?

  1. A. 36
  2. B. 17
  3. C. 8
  4. D. 7

Correct answer: B. 17

Each adjacent swap removes exactly one inversion, so the swap count equals the 17 inversions of the input. Counting comparisons gives 9·8/2 = 36, counting the n − 1 = 8 passes gives 8, and selection sort would need only 7 swaps.

More Coding Interview Problems questions

Exams that ask this topic