0
0
DSA Typescriptprogramming~3 mins

Why Binary Search Iterative Approach in DSA Typescript?

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?

The Scenario

Imagine you have a huge phone book with thousands of names sorted alphabetically. You want to find the phone number for a friend. If you start from the first page and look at every name one by one, it will take a very long time.

The Problem

Searching one by one is slow and tiring. It wastes time because you check many names unnecessarily. Also, it is easy to lose your place or make mistakes when flipping through so many pages.

The Solution

Binary search helps by quickly cutting the search area in half each time. Instead of checking every name, you jump to the middle, decide if your friend's name is before or after, and then only search that half. This way, you find the name much faster and with fewer mistakes.

Before vs After
Before
function findName(names: string[], target: string): number {
  for (let index = 0; index < names.length; index++) {
    if (names[index] === target) {
      return index;
    }
  }
  return -1;
}
After
function binarySearch(names: string[], target: string): number {
  let left = 0;
  let right = names.length - 1;
  while (left <= right) {
    const middle = Math.floor((left + right) / 2);
    if (names[middle] === target) return middle;
    else if (names[middle] < target) left = middle + 1;
    else right = middle - 1;
  }
  return -1;
}
What It Enables

Binary search enables lightning-fast searching in sorted lists, making large data easy to handle.

Real Life Example

When you search for a word in a dictionary app, binary search helps find the word instantly instead of scanning every page.

Key Takeaways

Manual search checks every item, which is slow for big lists.

Binary search cuts the search space in half repeatedly for speed.

It works only on sorted lists but makes searching very efficient.