Data Structures & AlgorithmsModerateTCS NQT · sorting

Problem: What is the minimum number of operations to sort the array [4, 3, 2, 1] using only swaps of adjacent elements? Run the code.

Problem: What is the minimum number of operations to sort the array [4, 3, 2, 1] using only swaps of adjacent elements? Run the code.
a = [4, 3, 2, 1]
ops = 0
for i in range(len(a)):
    for j in range(len(a) - 1 - i):
        if a[j] > a[j + 1]:
            a[j], a[j + 1] = a[j + 1], a[j]
            ops += 1
print(ops)
What is printed?
  1. A. 4
  2. B. 3
  3. C. 10
  4. D. 6

Correct answer: D. 6

Adjacent swaps remove exactly one inversion each, and [4,3,2,1] has 6 inversions. Bubble sort performs one swap per inversion, so the count equals the inversion number.

More Coding Interview Problems questions

Exams that ask this topic