# JavaScript Binary Search Implementation

Here's a concise explanation of binary search in JavaScript, along with an example implementation.

## What is Binary Search?

Binary search is an efficient algorithm for finding a target value within a sorted array. It works by repeatedly dividing the search interval in half. If the target value is less than the middle element, it searches the left half; if it's greater, it searches the right half. This process continues until the target value is found or the interval is empty.

## Binary Search Algorithm Steps

- Initialize two pointers,
`left`

and`right`

, to the start and end of the array. - Calculate the
`mid`

index as the average of`left`

and`right`

. - Compare the middle element with the target:
- If they are equal, return the mid index.
- If the target is less than the middle element, move the right pointer to mid - 1.
- If the target is greater, move the left pointer to mid + 1.

- Repeat steps 2-3 until the target is found or the pointers cross.

js

1 function binarySearch(arr, target) {2 let left = 0;3 let right = arr.length - 1;45 while (left <= right) {6 const mid = Math.floor((left + right) / 2);78 if (arr[mid] === target) {9 return mid; // Target found10 }11 if (arr[mid] < target) {12 left = mid + 1; // Search right half13 } else {14 right = mid - 1; // Search left half15 }16 }1718 return -1; // Target not found19 }2021 // Example usage:22 const sortedArray = [1, 3, 5, 7, 9, 11, 13];23 const target = 7;24 const result = binarySearch(sortedArray, target);2526 console.log(result); // Output: 3 (index of the target)

This implementation provides a time complexity of $𝑂(log 𝑛)$, making it much more efficient than a linear search for large datasets.