Binary Search
Binary Search is defined as a searching algorithm used in a sorted array by repeatedly dividing the search interval in half.
export function binarySearch(value: number, numbers: number[]): number {
let left = 0;
let right = numbers.length - 1;
let resultIndex = -1;
while (left <= right) {
let mid = Math.round(left + (right - left) / 2);
if (numbers[mid] === value) {
resultIndex = mid;
break;
} else {
if (numbers[mid]! > value) {
right = mid - 1;
} else {
left = mid + 1;
}
}
}
return resultIndex;
}
// Usage
const BiNumbers: number[] = [1, 5, 7, 64, 777, 1000, 1002, 1003];
console.log('Found number at: ' + binarySearch(64, BiNumbers));