GATE Computer ScienceVery hardGATE CS

Bubble sort with early exit (the algorithm stops after a pass in which no swap occurs) sorts the array [6, 9, 3, 8, 0, 5, 2, 7, 1, 4] into ascending order. How many passes are performed, including the final pass that detects no swaps?

  1. A. 7
  2. B. 8
  3. C. 9
  4. D. 10

Correct answer: B. 8

In each pass an element moves left by at most one place, so the number of swapping passes is the largest number of bigger elements to the left of any element. Here that is 7 (for the element 1: 6, 9, 3, 8, 5, 2, 7). So 7 passes with swaps are needed, plus one final pass: 8.

More Programming and Data Structures (GATE) questions

Exams that ask this topic