Overview
Data Structures
Searching
Binary Search is an efficient search algorithm that works on sorted arrays by repeatedly dividing the search interval in half.
If the target value is less than the middle element, the search continues in the left half; otherwise, in the right half. This reduces the time complexity to O(log n).
// Binary Search in JavaScript
function binarySearch(arr, target) {
let left = 0, right = arr.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
const result = binarySearch([1, 3, 5, 7, 9], 5);
console.log(result); // Output: 2Binary search needs sorted data. New slots start as NULL — fill them in ascending order using Push or Insert below.
Repeatedly halves the range using the midpoint.
Binary search is used when you have a large, sorted dataset and want to find an item quickly without scanning every element.
A common example is looking up a word in a dictionary — you don’t start from the first page; you open around the middle and adjust based on alphabetical order.
// Simulating binary search use in dictionary const words = ["Apple", "Banana", "Grape", "Mango", "Peach"]; console.log(binarySearch(words, "Mango")); // Output: 3