ProgrammingVery hardTCS NQT · Accenture
Lomuto partition is applied to a = [3, 8, 2, 5, 1, 4] with the pivot equal to the last element. For j = 0 to n - 2: if a[j] <= pivot, then i is increased and a[i] and a[j] are swapped (a swap is counted even when i = j). Finally the pivot is swapped into position i + 1 (counted). What is the number of swaps printed?
Lomuto partition is applied to a = [3, 8, 2, 5, 1, 4] with the pivot equal to the last element. For j = 0 to n - 2: if a[j] <= pivot, then i is increased and a[i] and a[j] are swapped (a swap is counted even when i = j). Finally the pivot is swapped into position i + 1 (counted). What is the number of swaps printed?
pivot = a[n-1]; i = -1; swaps = 0
for j = 0 to n - 2
if a[j] <= pivot then i = i + 1; swap a[i], a[j]; swaps = swaps + 1
end for
swap a[i+1], a[n-1]; swaps = swaps + 1
Print swaps- A. 3
- B. 4
- C. 2
- D. 6
Correct answer: B. 4
Three values (3, 2, 1) are at most the pivot 4 and each triggers a counted swap, and placing the pivot adds one more, for 4 swaps. Leaving out the final placement gives 3, counting the values greater than the pivot gives 2, and the length 6 is unrelated.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- For the array a = [2, 9, 4, 7, 5, 6, 3] (indices 0 to 6), the procedure below computes the sum of the maximum values of all contiguous…
- Array a = [3, 1, 4, 1, 5, 9, 2, 6] is scanned from left to right. The procedure below counts the positions i (from 2 to n) where a[i] is…
- Array a = [5, 3, 8, 1] (length 4). The procedure below counts how many elements are leaders, where an element is a leader if it is…
- For the array a = [1, 2, 3, 5, 4] the next permutation (in lexicographic order) is computed by the standard procedure: find the last i…
- Array a = [3, 6, -2, -5, 7, 3]. The procedure below finds the largest product of two adjacent elements. What is printed? best = a[0] a[1]…
- The loop below prints the running count for i = 1, 4, 7, 10, ... up to and including 20 (i increases by 3 each time). What is the number…