Binary Search Guide: Comparing Recursive and Iterative Methods
A Deep Dive into Binary Search: Recursive vs. Iterative Techniques

What is Binary Search?
Binary search is a highly efficient algorithm used to locate a target value within a sorted array. By dividing the search space in half with each step, it reduces the time complexity to O(log n). In this blog, we'll explore both recursive and iterative solutions for binary search in TypeScript.
Recursive Solution
function search(nums: number[], target: number): number {
return binarySearch(nums, target, 0, nums.length - 1);
}
function binarySearch(nums: number[], target: number, left: number, right: number): number {
// Base case
if (left > right) return -1;
let mid = Math.floor((left + right) / 2);
if (nums[mid] === target) {
return mid;
}
else if (nums[mid] < target) {
return binarySearch(nums, target, mid + 1, right);
}
else {
return binarySearch(nums, target, left, mid - 1);
}
}
How the Recursive Solution Works:
Function Call:
search(nums, target)initializes the search by callingbinarySearchwith the full array bounds.Base Case: If
leftexceedsright, the target is not in the array, so return-1.Middle Index: Compute the middle index,
mid = Math.floor((left + right) / 2).Comparison:
If
nums[mid]equals the target, returnmid.If
nums[mid]is less than the target, search the right half by callingbinarySearchwith updated bounds.If
nums[mid]is greater than the target, search the left half by callingbinarySearchwith updated bounds.
Iterative Solution
The iterative solution uses a loop instead of recursive calls, which can be more efficient in terms of space since it avoids the overhead of multiple function calls.
function search(nums: number[], target: number): number {
let left = 0;
let right = nums.length - 1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (nums[mid] === target) {
return mid;
}
else if (nums[mid] < target) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
// Target is not found in the array
return -1;
}
How the Iterative Solution Works:
Initialize Pointers: Set
leftto the start of the array andrightto the end.Loop: Continue while
leftis less than or equal toright.Middle Index: Compute the middle index,
mid = Math.floor((left + right) / 2).Comparison:
If
nums[mid]equals the target, returnmid.If
nums[mid]is less than the target, updatelefttomid + 1.If
nums[mid]is greater than the target, updaterighttomid - 1.
Target Not Found: If the loop exits without finding the target, return
-1.
Time and Space Complexity
Time Complexity: Both recursive and iterative binary search have a time complexity of O(log n), where
nis the number of elements in the array.Space Complexity:
Recursive: O(log n) due to the call stack used in recursion.
Iterative: O(1) as it only uses a few variables.
Comment if I have committed any mistake. Let's connect on my socials. I am always open for new opportunities , if I am free :P



