Algorithms

How do you implement a binary search algorithm in Python?

Medium
15
Added
Binary search is an efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list that could contain the item, until you've narrowed down the possible locations to just one.

Solution Code

Algorithms
def binary_search(arr, target):
    low, high = 0, len(arr) - 1
    while low <= high:
        mid = (low + high) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1

# Example usage
arr = [2, 3, 4, 10, 40]
target = 10
result = binary_search(arr, target)
print(result)
Explanation
This code snippet demonstrates how to implement a binary search algorithm in Python.

Guided Hints

Ensure the array is sorted
Use two pointers for the range
Divide the range in half each iteration
Related Questions
Difficulty Distribution
Easy 25
Hard 33
Medium 116