function binarySearch(arr, key) {
let start = 0;
let end = arr.length - 1;
while (start <= end) {
let mid = Math.floor((start + end) / 2);
if (arr[mid] === key) {
return mid;
} else if (arr[mid] < key) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return -1;
}
This implementation of the binary search algorithm uses a while loop to repeatedly divide the input array in half, and compares the middle element with the key, until the key is found or the search range is exhausted.
It takes an array as the first argument and a key as the second argument, and returns the index of the key in the array if it's found and -1 if it's not found.
Here's an example of how the function can be used:
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(binarySearch(arr, 3)); // 2
console.log(binarySearch(arr, 11)); // -1