Data Structures & AlgorithmsModerateTCS NQT · Infosys pattern
Insertion sort counts element shifts. What is printed?
Insertion sort counts element shifts. What is printed?
a = [3, 7, 1, 5, 2]
shifts = 0
for i in range(1, len(a)):
key, j = a[i], i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j]; j -= 1; shifts += 1
a[j + 1] = key
print(a, shifts)- A. [1, 2, 3, 5, 7] 5
- B. [1, 2, 3, 5, 7] 6
- C. [1, 2, 3, 5, 7] 7
- D. [1, 2, 3, 5, 7] 4
Correct answer: B. [1, 2, 3, 5, 7] 6
The number of shifts equals the number of inversions: (3,1), (3,2), (7,1), (7,5), (7,2), (5,2) = 6. On sorted input insertion sort makes 0 shifts (O(n)); on reversed input n(n−1)/2.
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
- 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…
- What is printed? (two-pointer: remove all occurrences of a value in place) cpp vector<int> a = {3, 2, 2, 3, 4, 3, 5}; int w = 0; for (int…