Binary Search is an efficient algorithm used to find a specific value in a sorted array or list. It works by repeatedly dividing the search interval in half until the desired value is found or the end of the collection is reached.
This algorithm requires the data to be sorted, which makes it less flexible in some situations. However, it is much more efficient for large datasets compared to linear search.
Binary Search works by repeatedly cutting the search range in half:
If the value is not found, the algorithm returns -1.
By halving the search space each time, Binary Search is significantly more efficient than checking every element.
function binarySearch(arr, target) {
let left = 0;
let 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;
}
// Example usage
const values = [3, 7, 12, 19, 25, 31];
console.log(binarySearch(values, 19)); // 3
console.log(binarySearch(values, 8)); // -1