ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Delphi Recursive Binary Search

Delphi / Object Pascal

Goal -- WPM

Ready
Exercise Algorithm Area
1program SearchUtils;
2
3uses
4SysUtils;
5
6// Recursive helper function for binary search
7function BinarySearchRecursiveHelper(const Arr: array of Integer; Target: Integer; Low: Integer; High: Integer): Integer;
8var
9Mid: Integer;
10begin
11// Base case 1: If the search space is empty, the element is not found.
12if Low > High then
13begin
14Result := -1; // Element not found
15Exit;
16end;
17
18// Calculate the middle index.
19Mid := Low + (High - Low) div 2;
20
21// Base case 2: If the middle element is the target, return its index.
22if Arr[Mid] = Target then
23begin
24Result := Mid;
25Exit;
26end;
27
28// Recursive step: If the target is smaller than the middle element,
29// search in the left half.
30if Target < Arr[Mid] then
31begin
32Result := BinarySearchRecursiveHelper(Arr, Target, Low, Mid - 1);
33end
34// Recursive step: If the target is larger than the middle element,
35// search in the right half.
36else
37begin
38Result := BinarySearchRecursiveHelper(Arr, Target, Mid + 1, High);
39end;
40end;
41
42// Main function to initiate the recursive binary search.
43// Assumes the input array is sorted in ascending order.
44function RecursiveBinarySearch(const Arr: array of Integer; Target: Integer): Integer;
45begin
46// Handle edge case: empty array.
47if Length(Arr) = 0 then
48begin
49Result := -1;
50Exit;
51end;
52
53// Start the recursive search with the full array range.
54Result := BinarySearchRecursiveHelper(Arr, Target, 0, Length(Arr) - 1);
55end;
56
57// Example usage (optional, for testing)
58// var
59// SortedArray: array of Integer;
60// Index: Integer;
61// begin
62// SetLength(SortedArray, 7);
63// SortedArray[0] := 2;
64// SortedArray[1] := 5;
65// SortedArray[2] := 8;
66// SortedArray[3] := 12;
67// SortedArray[4] := 16;
68// SortedArray[5] := 23;
69// SortedArray[6] := 42;
70//
71// Index := RecursiveBinarySearch(SortedArray, 16);
72// if Index <> -1 then
73// Writeln('Element 16 found at index: ', Index)
74// else
75// Writeln('Element 16 not found.');
76//
77// Index := RecursiveBinarySearch(SortedArray, 99);
78// if Index <> -1 then
79// Writeln('Element 99 found at index: ', Index)
80// else
81// Writeln('Element 99 not found.');
82//
83// Index := RecursiveBinarySearch([], 5);
84// if Index <> -1 then
85// Writeln('Element 5 found at index: ', Index)
86// else
87// Writeln('Element 5 not found in empty array.');
88// end.
Algorithm description viewbox

Delphi Recursive Binary Search

Algorithm description:

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 that could contain the item, until you've narrowed down the possible locations to just one. This is commonly used in searching large datasets, databases, or sorted arrays for specific values.

Algorithm explanation:

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.

Pseudocode:

function RecursiveBinarySearch(sortedArray, target):
  return BinarySearchHelper(sortedArray, target, 0, length(sortedArray) - 1)

function BinarySearchHelper(sortedArray, target, low, high):
  if low > high:
    return -1 // Element not found

  mid = low + (high - low) / 2

  if sortedArray[mid] == target:
    return mid // Element found
  else if target < sortedArray[mid]:
    return BinarySearchHelper(sortedArray, target, low, mid - 1) // Search left half
  else:
    return BinarySearchHelper(sortedArray, target, mid + 1, high) // Search right half