Delphi Recursive Binary Search
program SearchUtils; uses SysUtils; // Recursive helper function for binary search function BinarySearchRecursiveHelper(const Arr: array of Integer; Target: Integer; Low: Integer; High: Integer): Integer; var Mid: Integer; begin // Base case 1: If the search space is empty, the e...
This Delphi code implements a recursive binary search algorithm. Binary search is an efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list th...
The `RecursiveBinarySearch` function, along with its helper `BinarySearchRecursiveHelper`, performs a binary search on a sorted array. The algorithm's correctness relies on the array being sorted. The `BinarySearchRecursiveHelper` function takes the array, the target value, and the current search bounds (`Low` and `High`) as input. The primary base case is when `Low > High`, indicating that the search interval has become empty, and the target is not present, returning -1. The second base case is when the middle element (`Arr[Mid]`) matches the `Target`, returning the `Mid` index. If the target is smaller than the middle element, the search continues recursively on the left half (`Low` to `Mid - 1`). Otherwise, it continues on the right half (`Mid + 1` to `High`). The time complexity is O(log N) because the search space is halved in each recursive call. The space complexity is O(log N) due to the recursion stack depth. An edge case handled is an empty input array, which immediately returns -1.
function RecursiveBinarySearch(sortedArray, target): return BinarySearchHelper(sortedArray, target, 0, length(sortedArray) - 1) function BinarySearchHelper(sortedArray, target, low, high): if low > high: return -1 // Ele...