Binary Search in Python. Binary Search is an efficient algorithm for finding a target value within a sorted array. This method is significantly faster than linear search, especially for large data sets. In Python, implementing Binary Search is straightforward, given the language’s concise syntax and powerful features.
Table of Contents
Understanding Binary Search
The essence of Binary Search lies in comparison and division. It starts with the entire array and then narrows down the search range by half with each step. This is done by comparing the target value with the middle elements of the current range. If the target value is less than the middle element, The search continues on the left half of the range. If it is greater, The search shifts to the right half. This process continues until the target value is found or the range has been narrowed down to zero.
Implementing Binary Search in Python
We can implement Binary Search in Python by using an iterative approach or a recursive approach. Both method’s implementation is given below-
Iterative Approach for Binary Search in Python
The iterative approach uses a loop to divide the search range in half repeatedly until the target is found or the search range is exhausted.
def BinarySearch_iterative(array, target):
low = 0
high = len(array)-1
while low<=high:
mid = (low + high)//2
if array[mid] == target:
return mid
elif array[mid]<target:
low = mid + 1
else:
high = mid - 1
return - 1
arr = [2,3,5,6,7,8]
target = 5
result = BinarySearch_iterative(arr,target)
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found in the array")
Binary Search by Recursion in Python
The recursive approach divided the problem into small instances of the same problem, each time with a reduced search range Until the target is found or the range is empty.
def BinarySearch_recursive(array, target, low, high):
if low > high:
return-1
mid = (low + high)//2
if array[mid] == target:
return mid
elif array[mid]<target:
return BinarySearch_recursive(array,target,mid+1,high)
else:
return BinarySearch_recursive(array, target, low, mid-1)
arr = [2,3,5,6,7,8]
target = 6
result = BinarySearch_recursive(arr,target,0,len(arr)-1)
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found in the array")
Advantages of Binary Search
Binary search is much more efficient than linear search for sorted arrays, especially as the size of the array increases. Its time complexity is O(log n)
, where n is the number of elements in the array.
Binary Search is a staple algorithm in the field of computer science due to its efficiency and simplicity. In Python, implementing Binary Search, whether iteratively or recursively is straightforward and can significantly improve the performance of search operations on sorted arrays.
Happy Coding & Learning
1 thought on “Binary Search in Python”