How to Implement a Binary Search in Python

87 views

How to Implement a Binary Search in Python

How to Implement a Binary Search in Python

I want to implement a binary search algorithm in Python. How can I do this for a sorted list?

solveurit24@gmail.com Changed status to publish February 16, 2025
0

Binary search is an efficient algorithm for finding an item from a sorted list of items.

  1. Steps in Binary Search:
    • Initialize two pointers: low and high.
    • While low ≤ high, find the middle element.
    • If the middle element is the target, return its index.
    • If the target is greater, adjust low to mid + 1.
    • If the target is smaller, adjust high to mid - 1.
  2. Code Example:

    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
    
    sorted_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    print(binary_search(sorted_list, 5))  # Output: 4
    


  3. Time Complexity:
    • Binary search has a time complexity of O(log n), making it very efficient for large datasets.
  4. Explanation:
    • This implementation assumes the list is sorted in ascending order.
    • Returns the index of the found element or -1 if not found.
solveurit24@gmail.com Changed status to publish February 16, 2025
0
You are viewing 1 out of 1 answers, click here to view all answers.