binary search algorithm in javascript

Here's the implementation of binary search algorithm in javascript:

function binarySearch(arr, target) {
  let low = 0;
  let high = arr.length - 1;

  while (low <= high) {
    const mid = Math.floor((low + high) / 2);

    if (arr[mid] === target) {
      return mid;
    } else if (arr[mid] < target) {
      low = mid + 1;
    } else {
      high = mid - 1;
    }
  }

  return -1;
}
320 chars
19 lines

Here's how to use the binarySearch function:

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const target = 5;

const index = binarySearch(arr, target);

console.log(index); // output: 4
139 chars
7 lines

The function takes two parameters, an array arr and a value to be searched target. It returns the index of the target in arr if found, otherwise it returns -1.

gistlibby LogSnag