Searching
Binary Search (Recursive)
Use the same binary-search window as the iterative lesson, but pass lo and hi through recursive calls.
Algorithm
Basic Implementation
basic.rb
arr = [1, 3, 5, 7, 9, 11, 13]
target = 11
def search(arr, target, lo, hi)
return -1 if lo > hi
mid = lo + (hi - lo) / 2
return mid if arr[mid] == target
return search(arr, target, mid + 1, hi) if arr[mid] < target
search(arr, target, lo, mid - 1)
end
puts search(arr, target, 0, arr.length - 1)
Complexity
- Time: O(log n)
- Space: O(log n) call stack
Implementation notes
search(arr, target, lo, hi)is a Ruby method that returns an integer index or-1; it does not mutate the array.- The base case is
return -1 if lo > hi, so an empty search window returns the miss sentinel immediately. mid = lo + (hi - lo) / 2uses Ruby integer division to produce an array index.- The method reads
arr[mid]directly for the equality check and then for the branch comparison. - On a match,
return midsends the found index back through the recursive call chain. - If
arr[mid] < target, the next call issearch(arr, target, mid + 1, hi); otherwise it searcheslothroughmid - 1. - The trace starts with bounds
(0, 6), seesarr[3] = 7, recurses right to(4, 6), then findsarr[5] = 11. puts search(arr, target, 0, arr.length - 1)prints the returned index5.
execution replay
The checked-in replay follows the language-neutral state table for `search-binary-recursive`.
cross-language comparison
This Ruby DSA version keeps the same data and final output as every other DSA book in this wave.