How to Implement a Binary Search in Python
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
Binary search is an efficient algorithm for finding an item from a sorted list of items.
- Steps in Binary Search:
- Initialize two pointers:
lowandhigh. - While
low≤high, find the middle element. - If the middle element is the target, return its index.
- If the target is greater, adjust
lowtomid + 1. - If the target is smaller, adjust
hightomid - 1.
- Initialize two pointers:
- 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
- Time Complexity:
- Binary search has a time complexity of O(log n), making it very efficient for large datasets.
- 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