function binarySearch(arr: number[], target: number): number {
// Initialize the left and right pointers
let left = 0;
let right = arr.length - 1;
// While there is a range to search
while (left <= right) {
// Calculate the middle index
const mid = Math.floor((left + right) / 2);
// Check if the middle element is the target
if (arr[mid] === target) {
return mid; // Target found, return index
}
// If the target is greater, ignore the left half
if (arr[mid] < target) {
left = mid + 1;
}
// If the target is smaller, ignore the right half
else {
right = mid - 1;
}
}
// Target not found, return -1
return -1;
}
// Example usage:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const target = 7;
const index = binarySearch(numbers, target);
console.log(`Index of ${target}:`, index); // Output: Index of 7: 6