How do you perform a binary search in a given array in TypeScript

TypeScript
x
19
function binarySearch(arr: number[], x: number) {
let start = 0;
let end = arr.length - 1;
while (start <= end) {
let mid = Math.floor((start + end) / 2);
if (arr[mid] === x) {
return mid;
} else if (arr[mid] < x) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return -1; // not found
}
🤖 Code Explanation
This code is written in TypeScript and is a function that performs a binary search on an array of numbers. The function takes two parameters, an array of numbers and a number to search for. The function returns the index of the number if it is found in the array, or -1 if it is not found.

More problems solved in TypeScript
















