Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Recursion Functions

Recursive function for Binary Search - Python Program

Example 1 :

def binary_search(lst, target, low=0, high=None): """Binary search recursively.""" if high is None: high = len(lst) - 1 if low > high: return -1 mid = (low + high) // 2 if lst[mid] == target: return mid elif lst[mid] > target: return binary_search(lst, target, low, mid-1) else: return binary_search(lst, target, mid+1, high) print(binary_search([1, 3, 5, 7, 9], 7))

Output

 
OUTPUT  :
3 

Example 2 :

def binary_search_recursive(arr, low, high, target): """ Performs a recursive binary search on a sorted array. Args: arr (list): The sorted list to search within. low (int): The lower bound of the current search space. high (int): The upper bound of the current search space. target: The element to search for. Returns: int: The index of the target element if found, otherwise -1. """ if low > high: # Base case: Search space is exhausted return -1 mid = (low + high) // 2 # Calculate the middle index if arr[mid] == target: # Target found at the middle return mid elif arr[mid] > target: # Target is in the left half return binary_search_recursive(arr, low, mid - 1, target) else: # Target is in the right half return binary_search_recursive(arr, mid + 1, high, target) # Example Usage: sorted_list = [1, 5, 9, 13, 17, 21, 25, 29] target_element_found = 17 target_element_not_found = 10 # Search for an element present in the list index_found = binary_search_recursive(sorted_list, 0, len(sorted_list) - 1, target_element_found) if index_found != -1: print(f"Element {target_element_found} found at index: {index_found}") else: print(f"Element {target_element_found} not found.") # Search for an element not present in the list index_not_found = binary_search_recursive(sorted_list, 0, len(sorted_list) - 1, target_element_not_found) if index_not_found != -1: print(f"Element {target_element_not_found} found at index: {index_not_found}") else: print(f"Element {target_element_not_found} not found.")

Output

 
OUTPUT  :
Element 17 found at index: 4
Element 10 not found.