ProgrammingHardTCS NQT · Accenture
Insertion sort on the array [5, 2, 4, 6, 1, 3] shifts an element one place right each time it moves past a larger element. The procedure below counts those shifts. What is printed?
Insertion sort on the array [5, 2, 4, 6, 1, 3] shifts an element one place right each time it moves past a larger element. The procedure below counts those shifts. What is printed?
shifts = 0
for i = 1 to n - 1
key = a[i]; j = i - 1
while j >= 0 and a[j] > key
a[j+1] = a[j]; j = j - 1; shifts = shifts + 1
end while
a[j+1] = key
end for
Print shifts- A. 5
- B. 10
- C. 9
- D. 15
Correct answer: C. 9
Each shift removes one inversion, and this array has 9 inversions, so 9 shifts happen. Counting the outer passes gives 5, counting comparisons (including each failed test) gives 10, and adding n to the total gives 15.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Array a = [3, 8, 7, 2, 7]. A linear scan returns the 0-based index of the first occurrence of 7. What is printed? for i = 0 to n - 1 if…
- Binary search for the value 13 in the sorted array [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] uses lo = 0, hi = n - 1 and mid = (lo + hi) div 2…
- Array a = [8, 4, 2, 1, 7, 5]. The number of inversions (pairs i < j with a[i] > a[j]) is the number of out-of-order pairs, and merge sort…
- Prefix sums are computed for a = [4, 1, 7, 3, 2, 8] with P[0] = 0 and P[k] = a[1] + ... + a[k]. A range sum for 1-based positions l to r…
- Array a = [4, 1, 7, 3, 2, 8] (three queries are not needed here). The procedure below counts the elements that are strictly greater than…
- Array a = [1, 2, 3, 4, 5, 6, 7] is rotated to the right by k = 3 positions: each element moves k places to the right with wrap-around. The…