Binary Search in Python - Mastering the Recursive and Iterative Methods

04 May 2023 Balmiki Mandal 0 Python

Binary Search in Python with Recursive and Iterative Methods

In computer science, binary search is a search algorithm that finds the position of a target value within an ordered array. Binary search runs in logarithmic time in the worst case, making it more efficient than linear search. In this article, we will be discussing two methods of implementing binary search in python – recursive and iterative.

Recursive Binary Search in Python

Recursion is a powerful technique for solving problems, and binary search is no exception. To begin, we need to determine the base case. The base case will be when the start index is greater than or equal to the end index. When we reach this condition, we can either return the index (if the target is found) or -1 (if the target is not found). We also need to determine the midpoint for the array and check if the target is equal to the midpoint element. If it is, then we’re done and can return the midpoint index. Otherwise, we can split the array into two halves and recursively call the binary search function on the appropriate half.

Here is an example of a recursive implementation of binary search:

``` def binary_search_recursive(arr, start, end, x): # Base case if start > end: return -1 # Get the midpoint mid = (start + end) // 2 # Check if the element at mid is the target if arr[mid] == x: return mid # If not, call binary search on the appropriate half if arr[mid] > x: return binary_search_recursive(arr, start, mid-1, x) else: return binary_search_recursive(arr, mid+1, end, x) ```

Iterative Binary Search in Python

The iterative approach follows the same logic as the recursive approach. However, instead of using recursion, we use a while loop. We start by setting the start and end index to the beginning and end of the array respectively. Then, we calculate the midpoint and check if the target is equal to the midpoint element. If it is, then we’re done and can return the midpoint index. Otherwise, we can split the array into two halves and move the start and end indices accordingly.

Here is an example of an iterative implementation of binary search:

``` def binary_search_iterative(arr, x): # Set initial boundaries for the search start = 0 end = len(arr) - 1 # Loop until the boundaries cross each other while start <= end: # Calculate the midpoint mid = (start + end) // 2 # Check if the target is equal to the midpoint element if arr[mid] == x: return mid # Split the array into two halves and move the indices accordingly if arr[mid] > x: end = mid - 1 else: start = mid + 1 # Element not found return -1 ```

We have now discussed two methods for implementing binary search in python – recursive and iterative. Both of these methods are efficient, so it’s up to you which one to choose.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.