What if you could find anything in a huge list in just a few quick steps instead of searching forever?
Why Binary Search Recursive Approach in DSA Javascript?
Imagine you have a thick phone book and you want to find a friend's number. You start from the first page and check every name one by one until you find your friend.
This method is very slow and tiring because you might have to look through hundreds or thousands of pages. It wastes time and energy, especially if the book is very big.
Binary search uses the fact that the phone book is sorted. Instead of checking every page, you open the middle page and decide if your friend's name is before or after it. Then you repeat this on the smaller half, quickly narrowing down where the name is.
function findName(names, target) {
for (let i = 0; i < names.length; i++) {
if (names[i] === target) return i;
}
return -1;
}function binarySearch(names, target, left, right) {
if (left > right) return -1;
const mid = Math.floor((left + right) / 2);
if (names[mid] === target) return mid;
if (names[mid] > target) return binarySearch(names, target, left, mid - 1);
return binarySearch(names, target, mid + 1, right);
}This approach lets you find items in huge sorted lists very fast, saving time and effort.
When you search for a word in a dictionary app, it quickly jumps to the middle and narrows down the search instead of reading every word.
Manual search checks every item one by one, which is slow.
Binary search splits the list and searches only half each time.
Recursive binary search calls itself on smaller parts until it finds the item or ends.