The time complexity of binary search is:a)O(log n)b)O(n)c)O(n2)d)O(1)C...
Binary search has a time complexity of O(log n), where n is the number of elements in the sorted array.
View all questions of this test
The time complexity of binary search is:a)O(log n)b)O(n)c)O(n2)d)O(1)C...
Time Complexity of Binary Search
Binary search is a classic searching algorithm that efficiently finds the position of a target value within a sorted array. It follows the principle of divide and conquer, repeatedly dividing the search space in half until the target value is found or determined to be absent. The time complexity of binary search is O(log n), where n is the number of elements in the sorted array.
Divide and Conquer Approach
Binary search works by comparing the target value with the middle element of the array. If they are equal, the search is successful. If the target value is smaller, the search continues on the left half of the array. If the target value is larger, the search continues on the right half of the array. This process is repeated until the target value is found or the search space is empty.
Logarithmic Time Complexity
The key insight behind the time complexity of binary search is that with each comparison, the search space is effectively halved. This leads to a logarithmic time complexity.
Let's consider an array of size n. In the worst case, binary search will have to perform log2(n) comparisons to find the target value. This is because each comparison reduces the search space by half.
For example, in an array of size 8, the search space is halved as follows:
- Step 1: [1, 2, 3, 4, 5, 6, 7, 8] -> [1, 2, 3, 4]
- Step 2: [1, 2, 3, 4] -> [3, 4]
- Step 3: [3, 4] -> [4]
In this case, it took 3 comparisons to find the target value. The maximum number of comparisons required for an array of size n is log2(n).
Example
Consider an array of size 16. The maximum number of comparisons required to find the target value using binary search is log2(16) = 4. This is because 2^4 = 16.
Thus, regardless of the size of the array, the time complexity of binary search is logarithmic - O(log n).