Binary Search Implementation

Efficient binary search algorithm with logarithmic time complexity

By Cojocaru David1d ago (Sep 13, 2025)
tutorial
python
algorithms

Binary Search Implementation

python
def binary_search(arr, target):
    """
    Performs binary search on a sorted array
    Time complexity: O(log n)
    Space complexity: O(1)
    """
    left, right = 0, len(arr) - 1
    
    while left <= right:
        mid = (left + right) // 2
        
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    
    return -1  # Element not found

# Example usage
numbers = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
result = binary_search(numbers, 7)
print(f"Element found at index: {result}")

Views

19

Lines

24

Characters

592

Likes

1

Details

Language
Python
Created
Sep 13, 2025
Updated
1d ago
Size
0.6 KB

Build your snippet library

Join thousands of developers organizing and sharing code snippets.

Binary Search Implementation - Snippets Library