Python Program to Implement Binary Search

Python Program to Implement Binary Search

When it comes to finding elements in a sorted dataset efficiently, binary search is one of the most important algorithms every programmer should know. Unlike linear search, which checks each element one by one, binary search quickly narrows down the search range by repeatedly dividing the dataset in half. Learning how to implement binary search in Python is a great way for beginners to understand efficient searching, algorithmic thinking, and performance optimization.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Binary search is widely used in many real-world applications, such as searching for a word in a dictionary, retrieving data from databases, or implementing features in software that require fast lookups. Understanding this algorithm is essential because it not only makes your programs faster but also strengthens your grasp of core programming concepts. In this article, we’ll explore multiple ways to implement binary search in Python, including iterative, recursive, and practical approaches, so beginners can follow along easily.

Program 1: Iterative Binary Search

This program demonstrates a basic iterative approach to binary search. It repeatedly checks the middle element of a sorted list and adjusts the search range until the target is found or the range is empty.

numbers = [2, 4, 6, 8, 10, 12, 14]
target = 10
left = 0
right = len(numbers) - 1
found = False

while left <= right:

    mid = (left + right) // 2

    if numbers[mid] == target:

        print(f"Element {target} found at index {mid}")
        found = True
        break

    elif numbers[mid] < target:
        left = mid + 1
    else:
        right = mid - 1


if not found:
    print(f"Element {target} not found in the list")

In this program, the while loop continues as long as the left index is less than or equal to the right index. By comparing the middle element with the target, the program efficiently narrows down the search space. Beginners can see how binary search reduces the number of comparisons compared to linear search, making it faster for larger datasets.

Program 2: Recursive Binary Search

Recursion provides a different approach to binary search. In this program, a function repeatedly calls itself with a smaller search range until it finds the target or determines that it is not present.

def binary_search_recursive(numbers, target, left, right):

    if left > right:
        return -1

    mid = (left + right) // 2

    if numbers[mid] == target:
        return mid
    elif numbers[mid] < target:
        return binary_search_recursive(numbers, target, mid + 1, right)
    else:
        return binary_search_recursive(numbers, target, left, mid - 1)


numbers = [1, 3, 5, 7, 9, 11]
target = 7
result = binary_search_recursive(numbers, target, 0, len(numbers) - 1)

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

Recursive binary search helps beginners understand how a problem can be broken into smaller subproblems. Each function call reduces the search space, demonstrating how recursion can achieve the same result as iteration while introducing concepts like base cases and function calls.

Program 3: Binary Search Using a Function (Iterative Approach)

This program wraps the iterative binary search logic in a function to make it reusable and organized.

def binary_search(numbers, target):

    left = 0
    right = len(numbers) - 1

    while left <= right:

        mid = (left + right) // 2

        if numbers[mid] == target:
            return mid
        elif numbers[mid] < target:
            left = mid + 1
        else:
            right = mid - 1

    return -1


numbers = [5, 10, 15, 20, 25]
target = 15
result = binary_search(numbers, target)

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

Using a function allows you to call the binary search code multiple times without rewriting it. This approach is particularly useful for beginners to see how code can be modular, organized, and easy to maintain.

Program 4: Binary Search in a Large Dataset

This example demonstrates binary search on a larger list, highlighting its efficiency and performance benefits.

numbers = list(range(0, 200, 2))  # 0, 2, 4, ..., 198
target = 78
left = 0
right = len(numbers) - 1
found = False

while left <= right:

    mid = (left + right) // 2

    if numbers[mid] == target:

        print(f"Element {target} found at index {mid}")
        found = True
        break

    elif numbers[mid] < target:
        left = mid + 1
    else:
        right = mid - 1


if not found:
    print(f"Element {target} not found in the list")

Even with 100 or more elements, binary search quickly locates the target. This example helps beginners appreciate why binary search is more efficient than linear search, especially for large, sorted datasets.

Program 5: Binary Search to Find First Occurrence of Duplicate Elements

When a list contains duplicate elements, Binary Search can be adapted to find the first occurrence of a target value. This program demonstrates that approach.

def binary_search_first_occurrence(arr, target):

    left, right = 0, len(arr) - 1
    result = -1

    while left <= right:

        mid = (left + right) // 2

        if arr[mid] == target:
            result = mid
            right = mid - 1  # Continue searching in the left half
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1

    return result


numbers = [1, 2, 4, 4, 4, 5, 6]
target = 4
result = binary_search_first_occurrence(numbers, target)

if result != -1:
    print(f"First occurrence of element {target} is at index {result}")
else:
    print(f"Element {target} not found")

Here, Binary Search is slightly modified to continue searching even after finding a match. By always moving to the left half when a match is found, the algorithm ensures that the first occurrence of the target is returned. Beginners can learn how simple modifications adapt Binary Search for different use cases.

Program 6: Binary Search Using Python’s bisect Module

Python’s bisect module provides a built-in way to perform binary search. This example shows how to use it for finding the index of an element.

import bisect

numbers = [2, 4, 6, 8, 10]
target = 6

index = bisect.bisect_left(numbers, target)

if index < len(numbers) and numbers[index] == target:
    print(f"Element {target} found at index {index}")
else:
    print(f"Element {target} not found in the list")

Using bisect simplifies binary search and reduces the chance of errors. Beginners can benefit from seeing how Python’s standard library offers optimized functions for common tasks, while still reinforcing the importance of working with sorted data.

Frequently Asked Questions (FAQ)

Binary search is efficient, but beginners often have questions. Here are some common ones with clear explanations.

Q1: What is binary search used for?
Binary search is used to find a specific element in a sorted list efficiently. It is essential for applications requiring fast lookups.

Q2: Can binary search be applied to unsorted data?
No, binary search requires a sorted list. Searching in an unsorted list will not give correct results.

Q3: Is binary search faster than linear search?
Yes, binary search reduces the number of comparisons by half each step, making it faster for large datasets.

Q4: Can recursion replace iteration in binary search?
Yes, recursive binary search achieves the same result as iteration but uses function calls to narrow the search range.

Q5: Why is binary search important for beginners?
Learning binary search teaches algorithmic thinking, efficiency, and how to optimize code, which are foundational programming skills.

Conclusion

Binary search is a fundamental algorithm that every beginner Python programmer should understand. By implementing it using iterative, recursive, function-based, and built-in approaches, you gain practical skills for searching efficiently in sorted datasets. Each approach teaches different programming concepts, from loops to recursion and using Python’s standard library.

Practicing these programs helps you understand lists, control flow, and optimization. Start with simple iterations, explore recursion, and then try built-in functions to see how Python handles binary search. The more you practice, the stronger your foundation will be for advanced algorithms and real-world programming tasks requiring fast and efficient searching.

Scroll to Top