Discover why searching smart beats searching hard every time!
Binary Search vs Linear Search Real Cost Difference in DSA Typescript - Why the Distinction Matters
Imagine you have a huge phone book with thousands of names. You want to find a friend's number. If you look at each name one by one from the start, it will take a long time.
Searching one by one is slow and tiring. If the list is very long, it wastes a lot of time and effort. You might lose patience or make mistakes while checking each name.
Binary search uses the fact that the list is sorted. It quickly cuts the search area in half each time, so you find the name much faster without checking every entry.
function linearSearch(arr: number[], target: number): number {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) return i;
}
return -1;
}function binarySearch(arr: number[], target: number): number {
let left = 0, right = arr.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
else if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}It enables lightning-fast searching in large sorted lists, saving time and effort.
When you search for a word in a dictionary app, it uses binary search to quickly find the word instead of checking every word from the start.
Linear search checks items one by one, which is slow for big lists.
Binary search splits the list and quickly narrows down the search.
Using binary search on sorted data saves a lot of time.