ProgrammingHardTCS NQT · Accenture pattern
What is the time complexity of binary search on a sorted array of n elements?
What is the time complexity of binary search on a sorted array of n elements?
Function binarySearch(Array arr, Integer target)
Integer lo = 0, hi = length(arr) - 1
while (lo <= hi)
Integer mid = (lo + hi) / 2
if (arr[mid] == target)
return mid
else if (arr[mid] < target)
lo = mid + 1
else
hi = mid - 1
end if
end while
return -1
End Function- A. O(n)
- B. O(n^2)
- C. O(log n)
- D. O(1)
Correct answer: C. O(log n)
Each iteration discards half of the remaining search range, so the number of iterations needed to shrink n elements down to 0 or 1 is O(log n).
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- 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)…
- 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] =…