GATE Computer ScienceModerateGATE CS (PYQ pattern)

Cocktail-shaker sort is applied to [5, 1, 4, 2, 8, 0, 3]: sweeps alternate left-to-right and right-to-left over the unsorted part (each completed sweep fixes one more end element) and the algorithm stops after the first sweep that makes no exchange. How many sweeps are executed, including that final one?

  1. A. 6
  2. B. 4
  3. C. 5
  4. D. 7

Correct answer: C. 5

Sweep 1 (→): [1,4,2,5,0,3,8]. Sweep 2 (←): [0,1,4,2,5,3,8]. Sweep 3 (→): [0,1,2,4,3,5,8]. Sweep 4 (←): [0,1,2,3,4,5,8]. Sweep 5 (→) makes no exchange, so 5 sweeps. Plain bubble sort with early exit needs 6 passes here, because the small key 0 moves left only one place per pass.

More Algorithms questions

Exams that ask this topic