Python Binary Search


Binary Search is an efficient algorithm to find a value in a sorted list by repeatedly dividing the search interval in half.

It’s faster than linear search but only works on sorted data.


🔹 Binary Search Logic

  1. Find the middle of the list

  2. If the middle value equals the target → return index

  3. If the target is smaller → search the left half

  4. If the target is larger → search the right half

  5. Repeat until found or range becomes empty


🔹 Iterative Binary Search in Python

def binary_search(arr, target):
    low = 0
    high = 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
numbers = [10, 20, 30, 40, 50, 60, 70]
target = 40

result = binary_search(numbers, target)
print("Found at index:", result)

✅ Output:

Found at index: 3

🔹 Recursive Binary Search

def binary_search_recursive(arr, low, high, target):
    if low > high:
        return -1
    mid = (low + high) // 2
    if arr[mid] == target:
        return mid
    elif arr[mid] > target:
        return binary_search_recursive(arr, low, mid - 1, target)
    else:
        return binary_search_recursive(arr, mid + 1, high, target)

🔹 Time Complexity

Case Time
Best Case O(1)
Worst Case O(log n)
Average O(log n)

🔹 Use Cases

  • Searching in sorted arrays/lists

  • Dictionary search (like Python’s bisect module)

  • Logarithmic time search

  • Finding boundaries in numerical ranges


Practice Questions

Q1. Write a Python program to perform binary search on a sorted list of 10 elements.

Q2. Write a Python program to modify the binary search function to return True or False instead of index.

Q3. Write a Python program to accept a list and a target value from the user and search using binary search.

Q4. Write a Python program to implement binary search using recursion.

Q5. Write a Python program to count and print the number of comparisons made during binary search.

Q6. Write a Python program to return all occurrences of the target value in case of duplicates.

Q7. Write a Python program to perform binary search on a descending sorted array (reverse order logic).

Q8. Write a Python program to use the bisect module to find insertion point of a value in a sorted list.

Q9. Write a Python program to compare execution time of binary search vs linear search.

Q10. Write a Python program to handle invalid input types using try/except in binary search.


Go Back Top