search algorithm in typescript

To implement a search algorithm in TypeScript, there are two common search methods: binary search and linear search.

Linear Search

Linear search is a simple search algorithm that checks every element of an array. It starts with the first element and compares it with the search value. If the value is found, the index is returned. Otherwise, the search continues to the next element until the end of the array is reached.

index.ts
function linearSearch(arr: number[], searchVal: number): number {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === searchVal) {
      return i;
    }
  }
  return -1; // searchVal was not found in the array
}

const arr = [1, 2, 3, 4, 5];
console.log(linearSearch(arr, 3)); // outputs 2
298 chars
12 lines

Binary Search

Binary search is a more efficient search algorithm for sorted arrays. It works by dividing the array in half and checking if the middle element is the search value. If the middle element is not the search value, the algorithm determines which half of the array the search value could be in and only searches that half, repeating the process recursively until the search value is found or determined to not be in the array.

index.ts
function binarySearch(arr: number[], searchVal: number): number {
  let left = 0;
  let right = arr.length - 1;
  while (left <= right) {
    const mid = Math.floor((left + right) / 2);
    if (arr[mid] === searchVal) {
      return mid;
    } else if (searchVal < arr[mid]) {
      right = mid - 1;
    } else {
      left = mid + 1;
    }
  }
  return -1; // searchVal was not found in the array
}

const arr = [1, 2, 3, 4, 5];
console.log(binarySearch(arr, 3)); // outputs 2
478 chars
19 lines

gistlibby LogSnag