Binary search
An algorithm that uses decrease and conquer to efficiently search a sorted array for a target value.
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;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
binarySearch(['a', 'b', 'c', 'd', 'e'], 'd');
3
binarySearch(['a', 'b', 'c', 'd', 'e'], 'f');
-1