binary search in javascript

Binary search is a search algorithm that works efficiently for sorted arrays. Here's an implementation of binary search in JavaScript.

index.tsx
function binarySearch(arr, x) {
  let left = 0;
  let right = arr.length - 1;
  while (left <= right) {
    let mid = Math.floor((left + right) / 2);
    if (arr[mid] === x) {
      return true;
    } else if (arr[mid] < x) {
      left = mid + 1;
    } else {
      right = mid - 1;
    }
  }
  return false;
}
312 chars
16 lines

The function takes two arguments: the array to search and the value to search for, and returns true if the value is found or false otherwise. The algorithm works by repeatedly dividing the search interval in half until the value is found or the search interval is empty.

gistlibby LogSnag