Binary search is usually the first "real" algorithm people learn in DSA, and for good reason: it's simple, it's fast, and it teaches the core idea behind a huge number of more advanced algorithms — solve a big problem by repeatedly cutting it in half.
The Problem It Solves
You have a sorted list of numbers and you want to know if a target value exists in it (and where). The naive approach — checking every element one by one — is O(n). Binary search does it in O(log n), which is dramatically faster for large lists.
How It Works
Look at the middle element of the list.
If it matches the target, you're done.
If the target is smaller, repeat the search on the left half.
If the target is larger, repeat the search on the right half.
Keep going until you find it, or the range becomes empty (not found).
Every step throws away half the remaining list — that's why it's so fast. Searching 1,000,000 sorted items takes at most ~20 comparisons.
JavaScript Implementation
function binarySearch(arr, target) {
let low = 0;
let high = arr.length - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (arr[mid] === target) {
return mid; // found it
} else if (arr[mid] < target) {
low = mid + 1; // search the right half
} else {
high = mid - 1; // search the left half
}
}
return -1; // not found
}
const sortedNums = [1, 3, 4, 6, 7, 8, 10, 13, 14, 18, 19, 21, 24];
console.log(binarySearch(sortedNums, 14)); // 8
Why the Array Must Be Sorted
Binary search only works because a sorted array guarantees that everything to the left of the middle is smaller, and everything to the right is bigger. That guarantee is what lets you safely discard half the list every time. Run it on an unsorted array and it will give you wrong answers.
Common Interview Variations
Find the first or last occurrence of a repeated value.
Search in a sorted array that's been rotated.
Find the smallest value that satisfies a condition ("search on the answer").
Conclusion
Binary search turns an O(n) problem into an O(log n) one just by using the fact that the data is sorted. Once this pattern clicks, you'll start spotting places to apply it well beyond plain array searching. Next in this series: Sorting Algorithms Explained.
Image: AlwaysAngry / Wikimedia Commons (CC BY-SA 4.0)
Comments
Post a Comment