Efficient binary search algorithm with logarithmic time complexity
def binary_search(arr, target):
"""
Performs binary search on a sorted array
Time complexity: O(log n)
Space complexity: O(1)
"""
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1 # Element not found
# Example usage
numbers = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
result = binary_search(numbers, 7)
print(f"Element found at index: {result}")
Views
Lines
Characters
Likes