In a binary search algorithm, what is the time complexity of searching for an element?
a) O(log n)
b) O(n)
c) O(n^2)
d) O(1)
Answer:
a) O(log n)
Explanation:
Binary search is a divide-and-conquer algorithm that splits the search space in half with each comparison, resulting in a time complexity of O(log n). It works efficiently on sorted arrays or lists.
At each step, the algorithm compares the target value with the middle element and discards half of the search space based on the comparison. This ensures that the search process is logarithmic in nature.
Binary search is much faster than linear search O(n) for large datasets, but it requires that the data be sorted beforehand.
Reference:
DSA (Data Structures and Algorithms) MCQ Questions and Answers