Loading...
An efficient divide-and-conquer search algorithm that works on sorted arrays by repeatedly dividing the search interval in half.
Logarithmic time
Constant extra space
Element at middle
Array must be sorted
def binary_search(arr, target):
"""
Binary Search Algorithm
Time Complexity: O(log n)
Space Complexity: O(1)
Prerequisite: Array must be sorted
"""
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid # Element found
elif arr[mid] < target:
left = mid + 1 # Search right half
else:
right = mid - 1 # Search left half
return -1 # Element not found
# Recursive implementation
def binary_search_recursive(arr, target, left=0, right=None):
if right is None:
right = len(arr) - 1
if left > right:
return -1
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
return binary_search_recursive(arr, target, mid + 1, right)
else:
return binary_search_recursive(arr, target, left, mid - 1)
# Example usage
sorted_array = [11, 12, 22, 25, 34, 50, 64, 76, 88, 90]
target = 50
result = binary_search(sorted_array, target)
if result != -1:
print(f"Element {target} found at index {result}")
else:
print(f"Element {target} not found")
Aspect | Binary Search | Linear Search |
---|---|---|
Time Complexity | O(log n) | O(n) |
Space Complexity | O(1) | O(1) |
Data Requirement | Must be sorted | No requirement |
Best for | Large sorted datasets | Small or unsorted data |
Implementation | More complex | Very simple |
Performance (1M elements) | ~20 comparisons | ~500,000 comparisons |