What is the time complexity of a binary search on a sorted array?
Practice Questions
Q1
What is the time complexity of a binary search on a sorted array?
O(n)
O(log n)
O(n log n)
O(1)
Questions & Step-by-Step Solutions
What is the time complexity of a binary search on a sorted array?
Step 1: Understand that binary search is used on a sorted array.
Step 2: Start with the entire array and find the middle element.
Step 3: Compare the middle element with the target value you are searching for.
Step 4: If the middle element is equal to the target, you found it!
Step 5: If the middle element is greater than the target, repeat the search on the left half of the array.
Step 6: If the middle element is less than the target, repeat the search on the right half of the array.
Step 7: Each time you repeat the search, you are cutting the number of elements to search in half.
Step 8: This halving process continues until you find the target or the search space is empty.
Step 9: The number of times you can halve the array is logarithmic in relation to the number of elements, which is why the time complexity is O(log n).