Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Count the swaps made by bubble sort and by selection sort on the same array.

Problem: Count the swaps made by bubble sort and by selection sort on the same array.
def bubble(a):
    a = a[:]; s = 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]; s += 1
    return s
def selection(a):
    a = a[:]; s = 0
    for i in range(len(a)):
        m = min(range(i, len(a)), key=a.__getitem__)
        if m != i: a[i], a[m] = a[m], a[i]; s += 1
    return s
print(bubble([4, 3, 5, 1, 2]), selection([4, 3, 5, 1, 2]))
What is printed?
  1. A. 7 4
  2. B. 4 7
  3. C. 10 4
  4. D. 7 3

Correct answer: D. 7 3

Bubble sort performs exactly one swap per inversion: (4,3), (4,1), (4,2), (3,1), (3,2), (5,1), (5,2) = 7. Selection sort makes at most n − 1 swaps: here it swaps 1 into place, then 2, then 3, i.e. 3 swaps and no more once 4 and 5 are already in position.

More Coding Interview Problems questions

Exams that ask this topic