Python Binary Search

Python Binary Search

Binary Search is a highly efficient searching algorithm. It works by repeatedly dividing the search interval in half. A key requirement for binary search is that the input list must be sorted.

Compared to Linear Search (O(n)), Binary Search is much faster, with a time complexity of O(log n).


How Binary Search Works

Imagine you're looking for a word in a dictionary. You don't start at the first page; you open it roughly to the middle. If your word comes before the words on that page, you know to look in the first half. If it comes after, you look in the second half. You repeat this process, halving the search area each time, until you find the word.

The algorithm follows these steps:

  1. Compare the target value with the middle element of the sorted list.
  2. If the target value matches the middle element, its index is returned.
  3. If the target value is less than the middle element, narrow the search to the lower half of the list.
  4. If the target value is greater than the middle element, narrow the search to the upper half of the list.
  5. Repeat steps 1-4 until the value is found or the search interval is empty.

Implementing Binary Search in Python

Here is an iterative implementation of the binary search algorithm.

Binary Search (Iterative)

def binary_search(data, target):
    """
    Performs binary search on a sorted list.
    Returns the index of the target if found, otherwise returns -1.
    """
    low = 0
    high = len(data) - 1
    while low <= high:
        mid = (low + high) // 2 // Find the middle index
        // Check if target is present at mid
        if data[mid] == target:
            return mid
        // If target is greater, ignore left half
        elif data[mid] < target:
            low = mid + 1
        // If target is smaller, ignore right half
        else:
            high = mid - 1
    return -1 // Target not found

// --- Usage --- // The list MUST be sorted my_list = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] target_value = 23

result = binary_search(my_list, target_value)

if result != -1: print(f"Element {target_value} is present at index {result}") else: print(f"Element {target_value} is not present in the list")


Time Complexity

Logarithmic Power: The power of O(log n) is staggering. To search a list of 1 million items, linear search might take up to 1 million comparisons. Binary search would take at most 20!


Exercise

?

What is the main prerequisite for performing a binary search?