Binary search is a highly efficient algorithm for finding an element in a sorted list. Each comparison reduces the search space by half, resulting in a time complexity of O(log n), where n is the number of elements in the list. Here's an example:
Example - Binary Search in Python:
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = left + (right - left) // 2 # Calculate the middle index
if arr[mid] == target:
return mid # Element found, return its index
elif arr[mid] < target:
left = mid + 1 # Adjust the left bound
else:
right = mid - 1 # Adjust the right bound
return -1 # Element not found
# Example usage:
sorted_list = [1, 3, 5, 7, 9, 11, 13, 15]
target = 7
result = binary_search(sorted_list, target)
if result != -1:
print(f"Element {target} found at index {result}")
else:
print(f"Element {target} not found in the list")
In this example, we implement binary search to find the index of the target element in a sorted list. The algorithm divides the search space in half until it finds the target element or concludes that it's not in the list. This makes binary search an efficient choice for searching in sorted data, such as arrays or lists.
Top comments (0)