What is the time complexity of searching for an element in a sorted array using
Practice Questions
Q1
What is the time complexity of searching for an element in a sorted array using binary search?
O(n)
O(log n)
O(n log n)
O(1)
Questions & Step-by-Step Solutions
What is the time complexity of searching for an element in a sorted array using binary search?
Step 1: Understand that binary search is used on sorted arrays.
Step 2: Know that binary search works by repeatedly dividing the search interval in half.
Step 3: Start with the entire array as the search interval.
Step 4: Compare the target element with the middle element of the array.
Step 5: If the target is equal to the middle element, you found it.
Step 6: If the target is less than the middle element, repeat the search on the left half of the array.
Step 7: If the target is greater than the middle element, repeat the search on the right half of the array.
Step 8: Each time you divide the array, you reduce the number of elements to search by half.
Step 9: This halving process continues until you find the element or the search interval is empty.
Step 10: 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).