CodeGym /Java Course /Python SELF EN /Recursive Binary Search

Recursive Binary Search

Python SELF EN
Level 57 , Lesson 2
Available

3.1 How Recursive Binary Search Works

Binary search is an algorithm for finding an element in a sorted array that works on the "divide and conquer" principle. It compares the target element with the element in the middle of the array and decides which half of the array to continue searching in. Recursive binary search repeats this process by calling itself with updated array boundaries.

Algorithm steps:

  1. Compare the target element with the element in the middle of the array.
  2. If the middle element matches the target, return its index.
  3. If the target element is smaller, repeat the search in the left half of the array.
  4. If the target element is larger, repeat the search in the right half of the array.
  5. Repeat the process until the element is found or the array is exhausted.

Recursive Binary Search Implementation

Example in Python:


def binary_search_recursive(arr, target, left, right):
    if left > right:
        return -1  # Base case: element not found
            
    mid = (left + right) // 2  # Find the middle of the array
            
    if arr[mid] == target:
        return mid  # Base case: element found
    elif arr[mid] < target:
        return binary_search_recursive(arr, target, mid + 1, right)  # Search in the right half
    else:
        return binary_search_recursive(arr, target, left, mid - 1)  # Search in the left half
        
# Example usage:
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
target = 7
result = binary_search_recursive(arr, target, 0, len(arr) - 1)
print(f"Element found at position: {result}")  # Outputs: Element found at position: 6
        

3.2 Comparison With Iterative Binary Search

Iterative Binary Search:


def binary_search_iterative(arr, target):
    left, right = 0, len(arr) - 1
            
    while left <= right:
        mid = (left + right) // 2
                
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
            
    return -1  # Element not found
        
# Example usage:
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
target = 7
result = binary_search_iterative(arr, target)
print(f"Element found at position: {result}")  # Outputs: Element found at position: 6
        

Comparison:

Simplicity of implementation:

  • The recursive algorithm is usually simpler and shorter, but requires an understanding of recursive calls.
  • The iterative algorithm uses a loop, making it easier for beginners.

Memory:

  • The recursive algorithm uses a call stack, which can increase memory usage with large arrays.
  • The iterative algorithm uses a constant amount of memory, making it more efficient in terms of memory usage.

Performance:

  • Both algorithms have a time complexity of O(log n).
  • The recursive algorithm might be slower due to the overhead of recursive calls, especially if the recursion depth is large.

3.3 Example Tasks for Recursive Binary Search

Recursive binary search is a powerful algorithm that helps quickly find elements in sorted arrays. It is based on the "divide and conquer" principle and uses recursion to break the task into smaller sub-tasks.

Comparing the recursive and iterative approaches shows that each has its pros and cons depending on the specific task. Understanding these algorithms and their use cases allows for effective search problem-solving in programming.

For example, such as:

Searching an element in a sorted array:

Finding a specific element in an array of numbers, like test scores, database lookups by sorted keys, and so on.

Checking for element presence:

Checking if a certain value is present in a list of allowed users, IDs, and so on.

Finding the closest value:

Finding the element closest to a given value in an array, like searching for the nearest store, station, and so on.

Optimization:

Solving tasks that require finding the optimal value in a sorted array, like finding the minimum or maximum point in functions.

2
Task
Python SELF EN, level 57, lesson 2
Locked
Recursive Search
Recursive Search
2
Task
Python SELF EN, level 57, lesson 2
Locked
Close Friend
Close Friend
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION