ProgrammingHardGATE CS · Product company OA

How many swaps does this bubble sort make?

How many swaps does this bubble sort make?
int a[] = {3, 1, 4, 1, 5}, sw = 0;
for (int i = 0; i < 5; i++)
    for (int j = 0; j < 4 - i; j++)
        if (a[j] > a[j + 1]) { int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t; sw++; }
  1. A. 4
  2. B. 3
  3. C. 5
  4. D. 2

Correct answer: B. 3

Bubble sort swaps only adjacent out-of-order pairs, so it makes one swap per inversion. The inversions are (3, 1), (3, 1) and (4, 1): 3. The equal 1s never swap because the test is strict.

More C Programming questions

Exams that ask this topic