Data Structures & AlgorithmsModerateWipro · Accenture pattern

How many swaps does this bubble sort make, and how many passes run?

How many swaps does this bubble sort make, and how many passes run?
a = [5, 1, 4, 2, 8]
swaps = passes = 0
for i in range(len(a) - 1):
    passes += 1; swapped = False
    for j in range(len(a) - 1 - i):
        if a[j] > a[j + 1]:
            a[j], a[j + 1] = a[j + 1], a[j]; swaps += 1; swapped = True
    if not swapped: break
print(swaps, passes)
  1. A. 4 4
  2. B. 3 3
  3. C. 4 3
  4. D. 5 3

Correct answer: C. 4 3

Bubble sort swaps exactly once per inversion: (5,1), (5,4), (5,2), (4,2) → 4 swaps. Pass 1 gives [1, 4, 2, 5, 8], pass 2 [1, 2, 4, 5, 8], pass 3 makes no swap and stops early. Without the flag all 4 passes run.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic