Data Structures & AlgorithmsModerateTCS NQT · Infosys

A bubble sort performs left-to-right passes, swapping adjacent elements that are out of order, and stops after the first pass in which no swap happens. How many passes perform at least one swap when sorting [5, 1, 4, 2, 8]?

  1. A. 3
  2. B. 2
  3. C. 1
  4. D. 4

Correct answer: B. 2

Each pass moves an element left by at most one position, so the number of swapping passes equals the largest count of greater elements standing to the left of any element. Counting the final no-swap pass as well overcounts by one.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic