ProgrammingHardAccenture · Cognizant pattern

What is the worst-case time complexity of the following pseudocode (bubble sort) on an array of n elements?

What is the worst-case time complexity of the following pseudocode (bubble sort) on an array of n elements?
for (each i from 0 to n - 2)
    for (each j from 0 to n - 2 - i)
        if (arr[j] > arr[j + 1])
            swap(arr[j], arr[j + 1])
        end if
    end for
end for
  1. A. O(n)
  2. B. O(n log n)
  3. C. O(log n)
  4. D. O(n^2)

Correct answer: D. O(n^2)

The outer loop runs n-1 times, and the inner loop's length shrinks by 1 each pass but still sums to roughly n^2/2 comparisons overall, giving O(n^2) in the worst case (e.g. a reverse-sorted array).

More Pseudocode and Code Tracing questions

Exams that ask this topic