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
  1. A. 3
  2. B. 4
  3. C. 2
  4. 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.

More Pseudocode and Code Tracing questions

Exams that ask this topic