Discover why searching smarter saves you from endless waiting!
Binary Search vs Linear Search Real Cost Difference in DSA Javascript - Why the Distinction Matters
Imagine you have a huge phone book with thousands of names. You want to find one person's phone number. You start at the first page and look at every name one by one until you find the right one.
This way takes a lot of time because you might have to check many names before finding the right one. If the book is very big, it can be slow and tiring. Also, you can easily lose your place or make mistakes counting pages.
Binary search solves this by using the fact that the phone book is sorted. Instead of checking every name, it opens the book in the middle, decides if the name is before or after, and then repeats the process on the smaller half. This way, it finds the name much faster.
function linearSearch(array, target) {
for (let i = 0; i < array.length; i++) {
if (array[i] === target) return i;
}
return -1;
}function binarySearch(array, target) {
let left = 0, right = array.length - 1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (array[mid] === target) return mid;
else if (array[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}This difference lets us find items in huge sorted lists quickly, saving time and effort.
When searching for a word in a dictionary app, binary search helps find the word instantly instead of scrolling through every word.
Linear search checks items one by one, which is slow for big lists.
Binary search uses sorting to jump closer to the target quickly.
Binary search is much faster but needs the list to be sorted first.