Data Structures & AlgorithmsModerateTCS NQT · sorting

Problem: Using the bubble sort rule, what is the array after exactly one left-to-right pass over [3, 1, 2]? Run the code.

Problem: Using the bubble sort rule, what is the array after exactly one left-to-right pass over [3, 1, 2]? Run the code.
a = [3, 1, 2]
for j in range(len(a) - 1):
    if a[j] > a[j + 1]:
        a[j], a[j + 1] = a[j + 1], a[j]
print(a)
What is printed?
  1. A. [1, 3, 2]
  2. B. [1, 2, 3]
  3. C. [3, 1, 2]
  4. D. [2, 1, 3]

Correct answer: B. [1, 2, 3]

The first pass swaps 3 and 1, then 3 and 2, pushing the largest value to the end and giving [1, 2, 3]. Stopping after one comparison gives the trap [1, 3, 2].

More Coding Interview Problems questions

Exams that ask this topic