Binary Search is an efficient algorithm for finding an item in a sorted array. It works by repeatedly dividing the search interval in half. If the target value is less than the middle item of the interval, it continues to search in the lower half of the interval, and vice versa for the upper half. This process continues until the target item is found or the search interval is empty.
This functions returns the index of the item, or -1
if it was not found.
import { binarySearch } from "functional-algos";
const arr = ["apple", "banana", "cherry", "date", "elderberry"];
binarySearch(arr, "cherry"); // 2
Consider a sorted array of strings: ["apple", "banana", "cherry", "date", "elderberry"]
.
Let's say we are searching for the string cherry
.
- Start with the entire array. The middle element is
cherry
. - The target value
cherry
is equal to the middle element, so we return the index of the middle element, which is2
.
If we were searching for the string fig
instead, the search would go like this:
- Start with the entire array. The middle element is
cherry
. - The target value
fig
is greater than the middle elementcherry
, so we discard the lower half of the array and continue to search in the upper half:["date", "elderberry"]
. - Now the middle element is
date
. The target valuefig
is greater thandate
, so we discarddate
and continue to search in the remaining part of the array:["elderberry"]
. - The middle (and only) element now is
elderberry
. The target valuefig
is less thanelderberry
, so we discardelderberry
and are left with an empty array. This means the target valuefig
is not in the original array, so we return-1
.
Binary Search is a highly efficient searching algorithm with a time complexity of O(log n), where n is the number of elements in the array.
When the array length is even, there is no single middle element. Instead, there are two elements in the middle. This implementation opts to use the lower index of the two.