GATE Computer ScienceHardGATE CS (PYQ pattern)

Lomuto partition with the last element as pivot is applied to [34, 8, 64, 51, 32, 21, 78, 5, 40, 27]: i = -1; for j = 0 .. n-2, if a[j] <= pivot then i++ and swap a[i], a[j] (every such swap counts, even a self-swap); finally swap a[i+1] with the pivot. What is the final array, and how many swaps happen in the loop?

  1. A. 8 21 5 27 32 34 78 64 40 51; 2 swaps
  2. B. 8 21 5 27 32 34 78 64 40 51; 3 swaps
  3. C. 5 8 21 27 32 34 40 51 64 78; 3 swaps
  4. D. 8 21 5 27 34 32 78 64 40 51; 3 swaps

Correct answer: B. 8 21 5 27 32 34 78 64 40 51; 3 swaps

Pivot 27: the elements <= 27 are 8, 21, 5; swapping them to the front takes 3 loop swaps, then the pivot is placed at index 3.

More Programming and Data Structures (GATE) questions

Exams that ask this topic