What if you could find any name in a giant phone book in just a few steps?
Why Binary Search Recursive Approach in DSA Typescript?
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.
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.
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.
function linearSearch(array: number[], target: number): number {
for (let i = 0; i < array.length; i++) {
if (array[i] === target) return i;
}
return -1;
}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);
}It makes searching in sorted lists super fast, even if the list is huge.
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.
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.