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)- A. 4 4
- B. 3 3
- C. 4 3
- 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Insertion sort counts element shifts. What is printed? python a = [3, 7, 1, 5, 2] shifts = 0 for i in range(1, len(a)): key, j = a[i], i…
- Quick sort with Lomuto partition (last element as pivot). What is the array after the FIRST partition, and the pivot's final index? python…
- Merge two sorted halves and count comparisons. What is printed? python L, R = [1, 4, 6, 9], [2, 3, 10] i = j = comps = 0; out = [] while i…
- What is printed? (Python list aliasing) python a = [1, 2, 3] b = a c = a[:] b.append(4) c.append(5) print(a, len(b), len(c))
- What is printed? (frequency of the most common character, ties to the earliest) python s = "programming" best = max(s, key=s.count)…
- Sliding window: what is printed? (maximum sum of any 3 consecutive elements) c int a[] = {4, -1, 6, -2, 3, 5, -4, 2}; int n = 8, k = 3, s…