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?- A. 7 4
- B. 4 7
- C. 10 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
- Problem: Bottom-up heapify (max-heap) of an array; print the resulting array. python def heapify(a): n = len(a) def down(i): while True…
- Problem: Insert keys into a hash table of size 7 with open addressing and LINEAR probing, h(k) = k mod 7. python T = [None] 7 for k in…
- Problem: Double hashing with h1(k) = k mod 11 and h2(k) = 7 − (k mod 7); probe i is (h1 + i·h2) mod 11. Print the slots probed for key 58…
- Problem: Exponential (galloping) search: double the bound until a[hi] ≥ target, then binary search in (hi/2, hi]. Count the comparisons of…
- Problem: Count unique quadruplets (as value multisets) summing to target with sort + two nested loops + two pointers. python def four(a…
- Problem: For each element, the nearest smaller value to its LEFT (−1 if none), with a monotonic stack. python def leftsmaller(a): st, out…