binary search js
#algorithm#data-structures#recursion#search
👤cs
📅Last updated 16 days ago
Binary Search is an efficient algorithm to find an element in a sorted array.
It works by repeatedly dividing the search interval in half:
Compare the target value to the middle element.
If they are equal — the search is successful.
If the target is smaller — continue searching in the left half.
If the target is larger — continue searching in the right half.
Time Complexity: O(log n)
Requirement: The array must be sorted.
💻Source Code
// Binary Search Implementation in JavaScript
/**
* Performs binary search on a sorted array
* @param {number[]} arr - Sorted array to search in
* @param {number} target - Element to find
* @returns {number} Index of target if found, else -1
*/
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
// Continue searching while left <= right
while (left <= right) {
// Find the middle index
let mid = Math.floor((left + right) / 2);
// Check if middle element is the target
if (arr[mid] === target) {
return mid; // Found the target
}
// If target is smaller, ignore right half
else if (arr[mid] > target) {
right = mid - 1;
}
// If target is larger, ignore left half
else {
left = mid + 1;
}
}
// If not found
return -1;
}
// Example usage:
const numbers = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91];
const target = 23;
const result = binarySearch(numbers, target);
// Display result
if (result !== -1) {
console.log(`Element ${target} found at index ${result}`);
} else {
console.log(`Element ${target} not found in the array`);
}🔗Related Snippets
Similar code snippets you might find interesting
💬Comments (1)
🔒Please login to post comments
T
test⏰posted 12 days ago
8
⚡Actions
Share this snippet:
👤About the Author
c
cs
Active contributor
