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- A. O(n)
- B. O(n log n)
- C. O(log n)
- 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).
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 recursive pseudocode (computing n choose k via Pascal's identity), in the worst case, as a…
- What is the space complexity (auxiliary stack space) of the following recursive factorial function for input n? Function fact(Integer n)…
- What will be the output of the following pseudocode (anagram check via sorting)? Function isAnagram(String a, String b) return…
- What will be the output of the following pseudocode (duplicate detection using a set)? Function hasDuplicate(Array arr) Set seen = empty…
- What will be the output of the following pseudocode (maximum sum of any window of size k)? (Arrays are indexed from 0.) Integer arr[6] =…
- What will be the output of the following pseudocode (counting inversions, brute force)? (Arrays are indexed from 0.) Integer arr[5] = {2…