Binary search is an efficient algorithm used to search for an item in an ordered array or any other ordered data structure. It reduces the search space by half with each iteration, making it a highly optimized search algorithm.
To perform a binary search, follow these steps:
- Start with the ordered array and the item you need to search for.
- Calculate the middle index of the array by dividing the number of elements by 2.
- Compare the middle item with the item you are searching for.
- If the middle item is equal to the target item, return the index of the middle item.
- If the middle item is greater than the target item, discard the right part of the array and repeat the process with the left part.
- If the middle item is less than the target item, discard the left part of the array and repeat the process with the right part.
- Repeat steps 2-6 until the item is found or the search space is exhausted.
- If the item is not found, return
null
.
Binary search has a time complexity of O(log n)
, which means that the search time grows logarithmically with the size of the array.
Here is a possible implementation of the binary search algorithm in JavaScript:
const binarySearch = (list, item) => {
let low = 0;
let high = list.length - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
const guess = list[mid];
if (guess === item) {
return mid;
}
if (guess > item) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return null; // if not found
}
To use the binarySearch
function, pass in the ordered list and the item you want to find. It will return the index of the item if it is found, and null
if the item is not found.
Here are some examples of using the binarySearch
function:
console.log(binarySearch([1, 2, 3, 4, 5], 1)); // 0
console.log(binarySearch([1, 2, 3, 4, 5], 5)); // 4
console.log(binarySearch([1, 2, 3, 4, 5], 6)); // null
Binary search is a fundamental algorithm in computer science and is widely used in various applications. It offers a significant optimization compared to linear search for large datasets.