SwadhyAI Notes

All Python notes

Binary Search 🔎

Divide and Conquer

Binary Search is a fast search algorithm with run-time complexity of O(log n). It works on sorted arrays.

đŸ’ģ Implementation

python
def binary_search(arr, x):
    low = 0
    high = len(arr) - 1
    mid = 0

    while low <= high:
        mid = (high + low) // 2

        # If x is greater, ignore left half
        if arr[mid] < x:
            low = mid + 1

        # If x is smaller, ignore right half
        elif arr[mid] > x:
            high = mid - 1

        # x is present at mid
        else:
            return mid

    return -1

arr = [2, 3, 4, 10, 40]
x = 10
result = binary_search(arr, x)
print("Element is present at index", result)

🎮 Interactive Binary Search Demo

â„šī¸ Ready to Binary Search!
20
31
42
103
404
505
606
707
808
909

âš ī¸ Prerequisite

The list MUST be sorted for binary search to work.