What is the time complexity of binary search on a sorted array?
Practice Questions
1 question
Q1
What is the time complexity of binary search on a sorted array?
O(n)
O(log n)
O(n log n)
O(1)
Binary search divides the array in half with each step, leading to a time complexity of O(log n).
Questions & Step-by-step Solutions
1 item
Q
Q: What is the time complexity of binary search on a sorted array?
Solution: Binary search divides the array in half with each step, leading to a time complexity of O(log n).
Steps: 9
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).