What if you could find anything in a huge list in just a few quick steps?
Why Binary Search Iterative Approach in DSA Typescript?
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.
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.
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.
function findName(names: string[], target: string): number {
for (let index = 0; index < names.length; index++) {
if (names[index] === target) {
return index;
}
}
return -1;
}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;
}Binary search enables lightning-fast searching in sorted lists, making large data easy to handle.
When you search for a word in a dictionary app, binary search helps find the word instantly instead of scanning every page.
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.