Searching
Binary Search (Recursive)
Use the same binary-search window as the iterative lesson, but pass lo and hi through recursive calls.
Algorithm
execution replay
The checked-in replay follows the language-neutral state table for `search-binary-recursive`.
cross-language comparison
This Fortran DSA version keeps the same data and final output as every other DSA book in this wave.
Basic Implementation
basic.f90
Replay: real traced execution (multi-file project)
program search_binary_recursive
implicit none
integer :: arr(7) = [1, 3, 5, 7, 9, 11, 13]
integer :: target
target = 11
print '(I0)', search(arr, target, 0, 6)
contains
recursive integer function search(arr, target, lo, hi) result(pos)
integer, intent(in) :: arr(7), target, lo, hi
integer :: mid, value
if (lo > hi) then
pos = -1
return
end if
mid = lo + (hi - lo) / 2
value = arr(mid + 1)
if (value == target) then
pos = mid
else if (value < target) then
pos = search(arr, target, mid + 1, hi)
else
pos = search(arr, target, lo, mid - 1)
end if
end function search
end program search_binary_recursive
lo ← 0, hi ← 6, target ← 11
1program search_binary_recursive2 implicit nonevalues this step0lo6hi11targetmid ← 3, arr[mid] ← 7, next call ← (4, 6)
9integer, intent(in) :: arr(7), target, lo, hi10integer :: mid, value11if (lo > hi) thenvalues this step3mid7arr[mid](4, 6)next call0lo6himid ← 5, arr[mid] ← 11, result ← 5
9integer, intent(in) :: arr(7), target, lo, hi10integer :: mid, value11if (lo > hi) thenvalues this step5mid11arr[mid]5result4lo6histdout ← 5
5 target = 116 print '(I0)', search(arr, target, 0, 6)7containsvalues this step5stdout5result
Complexity
- Time: O(log n)
- Space: O(log n) call stack
Implementation notes
- Keep the explicit control flow. Library shortcuts would hide the state changes this lesson is meant to replay.
- The final output is intentionally small and deterministic for cross-language comparison.