ProgrammingHardTCS Digital · Infosys SP

An array of n elements is ALREADY sorted in increasing order. What is the time complexity of this pseudocode on it?

An array of n elements is ALREADY sorted in increasing order. What is the time complexity of this pseudocode on it?
for (each i from 1 to n - 1)
    j = i
    while (j > 0 AND a[j - 1] > a[j])
        swap(a[j - 1], a[j])
        j = j - 1
    end while
end for
  1. A. O(n)
  2. B. O(n²)
  3. C. O(n log n)
  4. D. O(log n)

Correct answer: A. O(n)

This is insertion sort. On sorted data the while test fails at once for every i (a[j − 1] ≤ a[j]), so each pass costs O(1) and the total is O(n). Its worst case, reverse-sorted data, is O(n²).

More Pseudocode and Code Tracing questions

Exams that ask this topic