0
0
DSA Typescriptprogramming~3 mins

Why Binary Search Recursive Approach in DSA Typescript?

Choose your learning style9 modes available
The Big Idea

What if you could find any name in a giant phone book in just a few steps?

The Scenario

Imagine you have a huge 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 it.

The Problem

This way takes a lot of time because you might have to look through hundreds or thousands of pages. It is slow and tiring, and you can easily lose your place or make mistakes.

The Solution

Binary search uses a smart trick: it looks at the middle page, decides if your friend's name is before or after, and then only searches that half. It repeats this until it finds the name or knows it is not there. This saves a lot of time and effort.

Before vs After
Before
function linearSearch(array: number[], target: number): number {
  for (let i = 0; i < array.length; i++) {
    if (array[i] === target) return i;
  }
  return -1;
}
After
function binarySearch(array: number[], target: number, left: number, right: number): number {
  if (left > right) return -1;
  const mid = Math.floor((left + right) / 2);
  if (array[mid] === target) return mid;
  else if (array[mid] > target) return binarySearch(array, target, left, mid - 1);
  else return binarySearch(array, target, mid + 1, right);
}
What It Enables

It makes searching in sorted lists super fast, even if the list is huge.

Real Life Example

When you search for a word in a dictionary app, it quickly jumps to the middle of the list and narrows down where the word could be, instead of checking every word.

Key Takeaways

Manual search checks every item one by one, which is slow.

Binary search splits the list and searches only the needed half each time.

This approach is much faster for sorted lists.