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- A. O(n)
- B. O(n²)
- C. O(n log n)
- 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²).
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What is the time complexity of the following pseudocode, as a function of n? Procedure f(Integer n) if (n <= 1) return end if for (each i…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Integer n = 7086351, s = 0, d…
- What will be the output of the following pseudocode? Procedure upd(Integer arr[], Integer n) // arrays are passed by reference arr[0] =…
- What will be the output of the following pseudocode? (& is bitwise AND) Integer x = 255, y = 256, c1 = 0, c2 = 0 while (x > 0) x = x & (x…
- What will be the output of the following pseudocode? Integer cnt = 0 Procedure go(Integer i, Integer s) if (s == 10) cnt = cnt + 1 return…
- What will be the output of the following pseudocode? Function G(Integer n) if (n == 0) return 0 end if return n - G(G(n - 1)) End Function…