2.6.2 Binary Search Recursive Method
2.6.2 Binary Search Recursive Method
Overview
This lecture explores the recursive implementation of the binary search algorithm, which follows the divide and conquer strategy. The discussion includes defining small and large problems, the steps of the algorithm, and how the algorithm handles each case.
Algorithm Definition
Parameters
- low: The lower index of the search range.
- high: The upper index of the search range.
- key: The element being searched.
Base Case (Small Problem)
- If there is only one element (
lowequalshigh), check if that element (a[low]) is the key.- If
a[low]equalskey, returnlow(index of the key). - If
a[low]is not the key, return-1indicating the key is not found.
- If
Recursive Case (Large Problem)
- Calculate the middle index:
mid = (low + high) / 2. - If
a[mid]equalskey, returnmid(key found). - If the key is less than
a[mid], recursively search the left subarray:rBinarySearch(low, mid - 1, key). - If the key is greater than
a[mid], recursively search the right subarray:rBinarySearch(mid + 1, high, key).
Divide and Conquer Strategy
This method divides the problem into smaller subproblems:
- Divide: The array is split into two halves around the midpoint.
- Conquer: Recursively apply binary search on the appropriate half.
- Combine: The base case or the recursive step returns the result directly without needing to combine results, as only one half is searched at a time.
Time Complexity Analysis
The recursive binary search algorithm's time complexity can be analyzed using a recurrence relation:
- Base Case: When the list size is 1 (
T(1)), it takes constant time, sayc. - Recursive Case: For more than one element, the problem is halved each time, leading to the recurrence relation
T(n) = T(n/2) + c.
Recurrence Relation
T(n) = T(n/2) + c- Where
crepresents the constant time for calculating the mid and checking conditions.
- Where
Using the Master Theorem, the time complexity is found to be Θ(log n), where the work done at each level of recursion adds up logarithmically due to the halving of the array size.
Summary
The recursive binary search algorithm efficiently searches for an element by repeatedly dividing the search interval in half. The key to understanding its efficiency lies in recognizing that each recursive call processes a smaller subset of the array, which significantly reduces the search space. This divide and conquer approach ensures that the algorithm achieves a logarithmic time complexity, making it highly efficient for large datasets.