0
0
DSA Javascriptprogramming~3 mins

Why Binary Search Recursive Approach in DSA Javascript?

Choose your learning style9 modes available
The Big Idea

What if you could find anything in a huge list in just a few quick steps instead of searching forever?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
function findName(names, target) {
  for (let i = 0; i < names.length; i++) {
    if (names[i] === target) return i;
  }
  return -1;
}
After
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);
}
What It Enables

This approach lets you find items in huge sorted lists very fast, saving time and effort.

Real Life Example

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.

Key Takeaways

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.