do a binary search in typescript

Here's an example implementation of the binary search algorithm in TypeScript:

index.ts
function binarySearch(arr: number[], target: number): number {
  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; // target not found
}

const arr = [1, 2, 4, 7, 9, 14, 17];
const target = 9;
console.log(binarySearch(arr, target)); // Output: 4
491 chars
23 lines

The binarySearch function takes in an array of numbers arr and a target number target, and returns the index of where the target number is located in the array using the binary search algorithm. If the target number is not found in the array, it returns -1.

The binary search algorithm works by repeatedly dividing the search interval in half, comparing the middle element of the interval to the target number, and eliminating the half in which the target cannot be located until the target is found or the interval is empty.

gistlibby LogSnag