Data Structures & AlgorithmsModerateTCS NQT · Infosys pattern

Bubble sort is written with a flag that stops it when a full pass makes no swap. What is its time complexity on an array that is already sorted?

  1. A. O(1)
  2. B. O(n)
  3. C. O(n²)
  4. D. O(n log n)

Correct answer: B. O(n)

The first pass makes n − 1 comparisons and no swap, so the algorithm stops: O(n). Without the flag it would still run all passes and take O(n²).

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

Exams that ask this topic